Reputation: 4617
https://codesandbox.io/s/rwm5x1w9r4
I have a demo in the above codesandbox. The first checkbox changes all the state to checked=true
second and third checkboxes just manage their own states. The state changes are working fine but the checkbox visuals are not changing. What do I have to do to make sure the checkboxes behave according to state change?
Upvotes: 2
Views: 8100
Reputation: 5514
If you check the console, you will see a warning:
Warning: A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
You are seeing this problem because you are not controlling the state of your other two checkboxes from the beginning, but try to manage it yourself later.
// but you are not initializing the checkbox ids "1" & "2", so they are uncontrolled.
state = {
"checkboxA" : true,
"checkboxB" : true,
"checkboxC" : true
}
What is happening behind the scenes is: the state of your uncontrolled component is maintained by the dom, i.e. outside of reacts scope. Later when you ask react to control the state, react is unsure of what is the right behaviour and bails out.
You can correct it by explicitly asking react to control the other two checkboxes, by setting them in state.
state = {
"checkboxA" : true,
"1" : true,
"2" : true
}
Here is the link to documentation for controlled and uncontrolled components in react official docs.
Update: Here is the sandbox I forked from yours: https://mm3379x0ox.codesandbox.io/
Upvotes: 7