React
by flek
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
let buttonRenders = 0;
const MyButton = (props) => {
buttonRenders++;
return (<button onClick={props.clickHandler}>{props.children}</button>);
};
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.uid = 0;
this.state = {
textColor: 'black',
todos: [],
dones: []
}
}
componentDidUpdate() {
console.log(buttonRenders);
}
keydownHandler(event) {
if (event.key === 'Enter') {
this.enter(event.target);
}
}
enter(input) {
this.add(input.value);
input.value = '';
}
createTodo = text => {
const id = ++this.uid;
return {
id,
text,
remove: () => this.remove(id)
}
}
add(text) {
const todos = [
this.createTodo(text),
...this.state.todos
];
this.setState({ todos });
}
remove(todo) {
let todos = [...this.state.todos];
todos.splice(todos.indexOf(todo), 1);
this.setState({ todos });
}
check(todo) {
this.remove(todo);
this.setState({ dones: [...this.state.dones, todo] });
}
clear() {
this.setState({ dones: [] });
}
toggleTextColor() {
this.setState({ textColor: this.state.textColor === 'red' ? 'black' : 'red' })
}
render() {
return (
<div style={{ color: this.state.textColor }}>
<label><input type="checkbox" onChange={this.toggleTextColor.bind(this)} /> Toggle Text Color</label><br/>
<input
type="text"
placeholder="what needs to be done?"
onKeyDown={this.keydownHandler.bind(this)}/>
<h2>Todos:</h2>
<ol>
{this.state.todos.map(todo => (
<li key={todo.id}>
<label>
<input type="checkbox" onChange={() => this.check(todo)} />
{todo.text}
<MyButton clickHandler={() => this.remove(todo)}>remove</MyButton>
</label>
</li>
))}
</ol>
<h2>Dones:</h2>
<ol>
...