Skip to content

Commit

Permalink
Warn if checkbox changes controlledness (from boolean checked to null)
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcin Mazurek committed Aug 26, 2016
1 parent f784a2d commit 5cf453f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/renderers/dom/client/wrappers/ReactDOMInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ function forceUpdateIfMounted() {

function isControlled(props) {
var usesChecked = props.type === 'checkbox' || props.type === 'radio';
return usesChecked ? props.checked !== undefined : props.value !== undefined;

This comment has been minimized.

Copy link
@jimfb

jimfb Aug 26, 2016

I think this just needs to use the != operator instead of the !== operator, to become return usesChecked ? props.checked !== undefined : props.value !== undefined;

if (usesChecked) {
return props.checked !== undefined && props.checked !== null;
}
return props.value !== undefined;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ describe('ReactDOMInput', function() {
);
});

it('should warn if controlled checkbox switches to uncontrolled', function() {
it('should warn if controlled checkbox switches to uncontrolled (checked is undefined)', function() {
var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
Expand All @@ -636,6 +636,20 @@ describe('ReactDOMInput', function() {
);
});

it('should warn if controlled checkbox switches to uncontrolled (checked is null)', function() {
var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
ReactDOM.render(stub, container);
ReactDOM.render(<input type="checkbox" checked={null} />, container);
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'A component is changing a controlled input of type checkbox to be uncontrolled. ' +
'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://fb.me/react-controlled-components'
);
});

it('should warn if controlled checkbox switches to uncontrolled with defaultChecked', function() {
var stub = <input type="checkbox" checked={true} onChange={emptyFunction} />;
var container = document.createElement('div');
Expand Down

0 comments on commit 5cf453f

Please sign in to comment.