React

by quangcanh2975

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;
}

Babel + JSX

class TodoItems extends Component {
  createTask = item => { // Day la mot function da duoc gan voi bien createTask
    return <li className='items' key={item.key} onClick={() => this.props.deleteItem(item.key)}>{item.text}</li> 
  }
  
  render() {
    let entries = this.props.entries; // Lay cac phan tu trong o App
    let itemsList = entries.map(this.createTask); // Array.map(function): thuc hien 1 mang len tung phan tu

    return (
      <div>
        <ul className='appList'>{itemsList}</ul>
      </div>
    );
  }
}

class TodoList extends Component {
  componentDidUpdate() {
    this.props.inputElement.current.focus()
  }
  render() {
    return (
      <div id="container">
        <form onSubmit={this.props.addItem}> {/* onSubmit when submit new task in the form */}
          <input id="input-box" placeholder='New Task' ref={this.props.inputElement} onChange={this.props.handleInput} value={this.props.currentItem.text} />
          <button type="submit">Add Task</button>
        </form>

      </div>
    );


  }
}

class App extends Component {
  inputElement = React.createRef()
  constructor() {
    super()
    this.state = {
      currentItem: { text: '', key: '' },
      itemsList: []
    }
    this.deleteItem = this.deleteItem.bind(this)
  }
  /* addItemToList Method: Add new task into the list */
  addItemToList = e => {
    e.preventDefault();
    if (this.state.currentItem.text !== '') {
      this.setState({
        itemsList: [...this.state.itemsList, this.state.currentItem],
        currentItem: { key: '', text: '' }
      })
    }
  }
  deleteItem = key => {
    this.setState({
      itemsList: this.state.itemsList.filter(item => item.key !== key)
    })

  }
  handleInput = e => {
    this.setState({
      currentItem: { text: e.target.value, key: Date.now() }
    })
  }
  render() {
    return (
      <div className="App">
        <TodoList addItem={this.addItemToList}
          handleInput={this.handleInput}
         ...