React is messing with me. I have a checkbox which ...
# react
b
React is messing with me. I have a checkbox which gets its “checked”-state from my component state:
Copy code
checked = state.active == true
I do have a custom
onChange
handler, which sets the state:
Copy code
val target = event.target as HTMLInputElement

setState {
    active = target.checked
}
When checking the checkbox, react throws this message:
Copy code
react_devtools_backend.js:6 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. More info: <https://fb.me/react-controlled-components>
1
t
Will it work with precalculated value?
Copy code
val target = event.target as HTMLInputElement
val newActive = target.checked

setState {
    active = newActive
}
b
same result. I tried to set
active
to true, when initialising:
Copy code
override fun State.init(props: Props) {
    active = true
}
And then the message appears, without me doing any click. Refreshing the page is enough
Holy moly… I got it. Just as there is
defaultValue
and
value
. There is also
defaultChecked
. When I change my code to:
Copy code
defaultChecked = state.active == true
the error disappears. Seen here: https://github.com/facebook/react/issues/6779#issuecomment-223818616
🎉 1
s