2
\$\begingroup\$

I would really like to improve, so any feedback is so appreciated!

Tasks.js

class Tasks extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tasks: [],
      nextId: null
    }
  }

  componentDidMount() {
    this.getTasks()
  }

  getTasks() {
    const tasks = List(this.state.tasks).push({ id: 1, name: 'Task 1'}, { id: 2, name: 'Task 2'}, { id: 3, name: 'Task 3'})
    this.setState({ tasks, nextId: 4 })
  }

  postTask() {
    const tasks = List(this.state.tasks).push({ id: this.state.nextId, name: `Task ${this.state.nextId}` })
    const nextId = this.state.nextId + 1
    this.setState({ tasks, nextId })
  }

  deleteTask(index) {
    const tasks = List(this.state.tasks).delete(index)
    this.setState({ tasks })
  }

  render() {
    return (
      <div>
        <div className='slide-fade'>
          {this.state.tasks.map((task, index) => (
            <Task
              key={task.id}
              deleteTask={() => this.deleteTask(index)}
              putTask={() => this.putTask(index)}
              name={task.name}
            />
          ))}
        </div>
        <button onClick={() => this.postTask()}>
          <i className='fa fa-plus fa-lg'></i>
        </button>
      </div>
    )
  }
}

Task.js

class Task extends Component {
  constructor(props) {
    super(props)
    this.state = {
      name: null,
      show: false,
      edit: false
    }
  }

  componentDidMount() {
    setTimeout(() => this.setState({ name: this.props.name, show: true }), 25)
  }

  onClickDelete() {
    this.setState({ show: false }, () => setTimeout(this.props.deleteTask, 250))
  }

  onClickEdit() {
    this.setState({ edit: true })
  }

  putTask() {
    this.setState({ edit: false })
  }

  onChangeInput(event) {
    this.setState({ name: event.target.value })
  }

  onKeyDownInput(event) {
    if(event.keyCode === 38) { // UP
      event.preventDefault()
    }
    if(event.keyCode === 13) { // ENTER
      this.putTask()
    }
  }

  render() {
    if(this.state.edit) {
      return (
        <input
          type='text'
          value={this.state.name}
          onChange={this.onChangeInput.bind(this)}
          onBlur={this.putTask.bind(this)}
          onKeyDown={this.onKeyDownInput.bind(this)}
          ref={input => input && input.focus()}
        />
      )
    }
    return (
      <div className={this.state.show ? 'item show' : 'item'}>
        <span className='item-text'>{this.state.name}</span>
        <span className='item-icons'>
          <i className='fa fa-pencil' onClick={() => this.onClickEdit()}></i>
          <i className='fa fa-ban' onClick={() => this.onClickDelete()}></i>
        </span>
      </div>
    )
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.