I created this simple TODO list, and when I want to check the checkbox I can't.
import React from 'react';
const TodoItem = React.createClass({
render() {
return (
<div>
<span>{this.props.todo}</span>
<input type="checkbox" checked={this.props.done} />
</div>
);
}
});
export default TodoItem;
The parent:
import React from 'react';
import TodoItem from './TodoItem';
import AddTodo from './AddTodo';
const TodoList = React.createClass({
getInitialState() {
return {
todos: [{
todo: 'some text',
done:false
},{
todo: 'some text2',
done:false
},
{
todo: 'some text3',
done:true
}]
};
},
addTodo (childComponent) {
var todoText = childComponent.refs.todoText.getDOMNode().value;
var todo = {
todo: todoText,
done:false
};
var todos = this.state.todos.concat([todo]);
this.setState({
todos:todos
});
childComponent.refs.todoText.getDOMNode().value = '';
},
render() {
var Todos = this.state.todos.map(function(todo) {
return (
<TodoItem todo={todo.todo} done={todo.done} />
)
});
return (
<div>
{Todos}
<AddTodo addTodo={this.addTodo}/>
</div>
);
}
});
export default TodoList;
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>