Skip to content

Instantly share code, notes, and snippets.

@hugoworks
Created Apr 16, 2018
Embed
What would you like to do?
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