2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactチュートリアル 〜reactでTODOアプリを作ろう〜

Posted at

この記事は、noteで販売している【脱初心者!!】ゼロから始めるReactのコードです。解説に関してはnoteをご購入ください。

コード

class App extends Component {
  constructor() {
    super()
    this.state={
      count: 0,
      todoList: [],
      value: "",
    }
  }

  onChange(key_value) {
    this.setState(key_value)
  }

  add(todoElement) {
    this.setState({
      todoList: this.state.todoList.concat(todoElement),
      value: "",
    })
  }

  handleDelete(id) {
    let todoList = this.state.todoList.concat()
    let index = 0
    todoList.map((element, idx) => {
      if (element.id == id) {
        index = idx
      }
    })
    todoList.splice(index, 1)
    this.setState({todoList: todoList})
  }

  render() {
    const todoListNode = this.state.todoList.map(element => {
      return (
        <TodoElement
          key={element.id}
          element={element}
          onDelete={this.handleDelete.bind(this)}
          {...this.state}
        />
      )
    })
    return (
      <div>
        <h1>TODO App</h1>
        <AddTodo
          {...this.state}
          onChange={this.onChange.bind(this)}
          add={this.add.bind(this)}
        />
        <ul>
          {todoListNode}
        </ul>
      </div>
    );
  }
}

class AddTodo extends React.Component {
  onChange(e) {
    const key_value = {
      value: e.target.value,
    }
    this.props.onChange(key_value)
  }

  add() {
    if (this.props.value) {
      const todoElement = {
        content: this.props.value,
        id: this.props.todoList.length + 1,
      }
      this.props.add(todoElement)
    }
  }

  render() {
    return(
      <div>
        <input
          type="text"
          value={this.props.value}
          onChange={this.onChange.bind(this)}
        />
        <button onClick={this.add.bind(this)}>追加</button>
      </div>
    )
  }
}

class TodoElement extends React.Component {
  onDelete() {
    this.props.onDelete(this.props.element.id)
  }
  render() {
    return(
      <li>
        <span>{this.props.element.content}</span>
        <button onClick={this.onDelete.bind(this)}>削除</button>
      </li>
    )
  }
}

今後、ドラッグ&ドロップで並び替えられる機能等を実装するかもです。

githubにも載せてあります。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?