Skip to content

Instantly share code, notes, and snippets.

@joeattardi
Created September 27, 2016 16:58
Show Gist options
  • Select an option

  • Save joeattardi/399cec72109ebdee985ae2ab8787c920 to your computer and use it in GitHub Desktop.

Select an option

Save joeattardi/399cec72109ebdee985ae2ab8787c920 to your computer and use it in GitHub Desktop.
Simple React Todo
class Todo extends React.Component {
render() {
const { todo } = this.props;
return (
<li className={todo.completed ? 'todo-completed' : ''}>
<input type="checkbox" onClick={this.props.onToggle.bind(null, todo)}/>
{todo.text}
</li>
);
}
}
class AddTodo extends React.Component {
constructor(props) {
super(props);
this.state = { text: '' };
}
handleChange(event) {
this.setState({ text: event.target.value });
}
handleAdd(event) {
event.preventDefault();
const newTodo = { text: this.state.text, completed: false }
this.props.onAdd(newTodo);
this.setState({ text: '' });
}
render() {
return (
<form>
<input type="text" value={this.state.text} onChange={this.handleChange.bind(this)} />
<button onClick={this.handleAdd.bind(this)}>Add Todo</button>
</form>
);
}
}
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = { todos: [
{
text: 'Feed the cats',
completed: false
}
] };
}
renderTodo(todo, index) {
return <Todo key={index} todo={todo} onToggle={this.toggleTodo.bind(this)} />;
}
toggleTodo(todo) {
this.setState({
todos: this.state.todos.map(theTodo => {
if (theTodo.text === todo.text) {
return { text: theTodo.text, completed: !theTodo.completed };
}
return theTodo;
})
});
}
addTodo(todo) {
this.setState({
todos: this.state.todos.concat([todo])
});
}
render() {
return (
<div>
<h1>Todo List</h1>
<ul>
{this.state.todos.map(this.renderTodo.bind(this))}
</ul>
<AddTodo onAdd={this.addTodo.bind(this)} />
</div>
);
}
}
ReactDOM.render(<TodoApp />, document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment