summaryrefslogtreecommitdiff
path: root/preact/demo/todo.js
blob: 189b4e80feeac6197aeb9723251f9252b3a476e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { createElement, Component } from 'preact';

let counter = 0;

export default class TodoList extends Component {
	state = { todos: [], text: '' };

	setText = e => {
		this.setState({ text: e.target.value });
	};

	addTodo = () => {
		let { todos, text } = this.state;
		todos = todos.concat({ text, id: ++counter });
		this.setState({ todos, text: '' });
	};

	removeTodo = e => {
		let id = e.target.getAttribute('data-id');
		this.setState({ todos: this.state.todos.filter(t => t.id != id) });
	};

	render({}, { todos, text }) {
		return (
			<form onSubmit={this.addTodo} action="javascript:">
				<input value={text} onInput={this.setText} />
				<button type="submit">Add</button>
				<ul>
					<TodoItems todos={todos} removeTodo={this.removeTodo} />
				</ul>
			</form>
		);
	}
}

class TodoItems extends Component {
	render({ todos, removeTodo }) {
		return todos.map(todo => (
			<li key={todo.id}>
				<button type="button" onClick={removeTodo} data-id={todo.id}>
					&times;
				</button>{' '}
				{todo.text}
			</li>
		));
	}
}