React.js can't change checkbox state
When you haven't specified an onChange
handler on your inputs React will render the input field as read-only.
getInitialState() {
return {
done: false
};
}
and
<input type="checkbox" checked={this.state.done || this.props.done } onChange={this.onChange} />
This is one of the top hits on Google for "React Component not updating", so although the answer has been well accepted, I think it could be misleading.
The checkbox
type doesn't require the onChange
. I am not sure if this has changed since the answer was posted (current version of React is v15 - 2016-04-20).
See the following example of it working without an onChange handler (see JSBIN):
class Checky extends React.Component {
render() {
return (<input type="checkbox" checked={this.props.checked} />);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { checked: true };
}
render() {
return (
<div>
<a href="#" onClick={ () => { this.setState({ checked: !this.state.checked }); }}>Toggle</a>
<hr />
<Checky checked={this.state.checked} />
</div>
);
}
}
React.render(<App />, document.body);
Another side note - a lot of answers (for similar questions) simply recommend "defaultChecked" - although this works, it is usually a half measure.
Just for others coming here. React now provides defaultChecked
:
<label htmlFor={id}>
<input
id={id}
type="checkbox"
defaultChecked={input.props.checked}
// disabled={input.props.disabled}
/>
<span className="custom-checkbox"></span>
{restChildren}
</label>