From 5cf453f9606a0f42b28705cdc33168766a1f2a75 Mon Sep 17 00:00:00 2001 From: Marcin Mazurek Date: Fri, 26 Aug 2016 14:27:05 +0100 Subject: [PATCH] Warn if checkbox changes controlledness (from boolean `checked` to null) --- .../dom/client/wrappers/ReactDOMInput.js | 5 ++++- .../wrappers/__tests__/ReactDOMInput-test.js | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/renderers/dom/client/wrappers/ReactDOMInput.js b/src/renderers/dom/client/wrappers/ReactDOMInput.js index dfa860a2dbe15..85f484986e0cf 100644 --- a/src/renderers/dom/client/wrappers/ReactDOMInput.js +++ b/src/renderers/dom/client/wrappers/ReactDOMInput.js @@ -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; + if (usesChecked) { + return props.checked !== undefined && props.checked !== null; + } + return props.value !== undefined; } /** diff --git a/src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js b/src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js index 797841df73e41..e701c6949f532 100644 --- a/src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js +++ b/src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js @@ -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 = ; var container = document.createElement('div'); ReactDOM.render(stub, container); @@ -636,6 +636,20 @@ describe('ReactDOMInput', function() { ); }); + it('should warn if controlled checkbox switches to uncontrolled (checked is null)', function() { + var stub = ; + var container = document.createElement('div'); + ReactDOM.render(stub, container); + ReactDOM.render(, 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 = ; var container = document.createElement('div');