Skip to content

Instantly share code, notes, and snippets.

@hugoworks
Created April 16, 2018 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugoworks/695267a155284b782d0feee22c3a35c7 to your computer and use it in GitHub Desktop.
Save hugoworks/695267a155284b782d0feee22c3a35c7 to your computer and use it in GitHub Desktop.
import { render } from "react-dom";
import React, { Component } from "react";
let id = 0;
const Todo = props => (
<li>
<input
type="checkbox"
checked={props.todo.checked}
onClick={props.onToggle}
/>
<button onClick={props.onDelete}>Delete</button>
<span>{props.todo.text}</span>
</li>
);
class App extends Component {
constructor() {
super();
this.state = {
todos: []
};
}
render() {
return (
<div>
<div>Todo Counter: {this.state.todos.length}</div>
<div>Unchecked Count: {this.state.todos.filter(todo => !todo.checked).length}</div>
<button onClick={() => this.addTodo()}>Add Todo</button>
<ul>
{this.state.todos.map(todo => (
<Todo
todo={todo}
onDelete={() => this.removeTodo(todo.id)}
onToggle={() => this.toggleTodo(todo.id)}
/>
))}
</ul>
</div>
);
}
addTodo() {
const text = prompt("TODO text please!");
this.setState({
todos: [...this.state.todos, { id: id++, text: text, checked: false }]
});
}
removeTodo(id) {
this.setState({
todos: this.state.todos.filter(todo => todo.id !== id)
});
}
toggleTodo(id) {
this.setState({
todos: this.state.todos.map(todo => {
if (todo.id !== id) return todo;
return {
...todo,
checked: !todo.checked
};
})
});
}
}
render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment