|
| 1 | +import React, { Component } from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import { connect } from 'react-redux'; |
| 4 | +import { addTodo, toggleTodo, removeTodo } from 'actions/todos'; |
| 5 | +import classnames from 'classnames'; |
| 6 | +import css from './index.scss'; |
| 7 | + |
| 8 | +const cx = classnames.bind(css); |
| 9 | + |
| 10 | +class TodosContainer extends Component { |
| 11 | + |
| 12 | + static propTypes = { |
| 13 | + todos: PropTypes.array.isRequired, |
| 14 | + dispatch: PropTypes.func.isRequired |
| 15 | + } |
| 16 | + |
| 17 | + submitTodo = (ev) => { |
| 18 | + const { dispatch } = this.props; |
| 19 | + const { todoText } = this.refs; |
| 20 | + |
| 21 | + ev.preventDefault(); |
| 22 | + dispatch(addTodo(todoText.value)); |
| 23 | + todoText.value = ''; |
| 24 | + } |
| 25 | + |
| 26 | + checkTodo = (id) => { |
| 27 | + const { dispatch } = this.props; |
| 28 | + |
| 29 | + dispatch(toggleTodo(id)); |
| 30 | + } |
| 31 | + |
| 32 | + removeTodo = (id) => { |
| 33 | + const { dispatch } = this.props; |
| 34 | + |
| 35 | + dispatch(removeTodo(id)); |
| 36 | + } |
| 37 | + |
| 38 | + render() { |
| 39 | + const { todos } = this.props; |
| 40 | + |
| 41 | + return ( |
| 42 | + <div> |
| 43 | + <h1>To-Dos</h1> |
| 44 | + <div className={css.todos}> |
| 45 | + {todos.map((todo, idx) => { |
| 46 | + const { id, text, completed } = todo; |
| 47 | + |
| 48 | + return ( |
| 49 | + <li key={idx} className={css.todo}> |
| 50 | + <span className={css.completeInput}> |
| 51 | + <input type="checkbox" onChange={() => this.checkTodo(id)} /> |
| 52 | + </span> |
| 53 | + <span className={cx(css.text, { [css.completed]: completed })}>{text}</span> |
| 54 | + <a onClick={() => this.removeTodo(id)} className={css.delete}>Remove</a> |
| 55 | + </li> |
| 56 | + ); |
| 57 | + })} |
| 58 | + </div> |
| 59 | + <form className={css.todoForm} onSubmit={this.submitTodo}> |
| 60 | + <input ref="todoText" type="text" placeholder="Add a todo..." /> |
| 61 | + <button type="submit">Add</button> |
| 62 | + </form> |
| 63 | + </div> |
| 64 | + ); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +const mapStateToProps = (state) => ({ |
| 69 | + todos: state.todos |
| 70 | +}); |
| 71 | + |
| 72 | +export default connect(mapStateToProps)(TodosContainer); |
0 commit comments