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

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    	todos: [
      	"Learn JavaScript",
        "Learn React",
        "Build something awesome"
      ],
      dones: []
    }
  }
  
  keydownHandler(event) {
    if (event.which === 13) {
      this.enter(event.target);
    }
  }

  enter(input) {
    this.add(input.value);
    input.value = '';
  }

  add(todo) {
    const todos = [todo, ...this.state.todos];
    this.setState({ todos });
  }

  remove(todo) {
    return () => {
      let todos = [...this.state.todos];
      todos.splice(todos.indexOf(todo), 1);
      console.log(todo, todos);
      this.setState({ todos });
    }
  }

  check(todo) {
    return () => {
      this.remove(todo)();
      this.setState({ dones: [...this.state.dones, todo] });
    }
  }

  clear() {
    this.setState({ dones: [] });
  }
  
  render() {
    return (
      <div>
        <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}>
            <label>
              <input type="checkbox" onChange={this.check(todo)} /> 
              {todo}
              <button onClick={this.remove(todo)}>remove</button>
            </label>
          </li>
        ))}
        </ol>
        <h2>Dones:</h2>
        <ol>
        {this.state.dones.map(done => (
          <li key={done}>
            <del>{done}</del>
          </li>
        ))}
        {!!this.state.dones.length && <button onClick={this.clear.bind(this)}>clear</button>}
        </ol>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))