LoginSignup
8
4

More than 5 years have passed since last update.

React ToDoリスト シンプルなサンプル

Last updated at Posted at 2018-05-04

よくあるToDoリストのサンプル。
最初はRedux、Flux的な要素は抜きで。

index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import ToDoList from './list';

const list = [];
ReactDOM.render(
  <ToDoList toDoList={list}/>,
  document.querySelector('#root')
);
list.jsx
import React from 'react';

class ToDoList extends React.Component{

  constructor(props){
    super(props);
    this.state = {
      toDoList: props.toDoList,
      textTitle: '',
      textContent: ''
    };
  } 

  addToDo(){
    let list = this.state.toDoList;
    list.push({ title: this.state.textTitle, content: this.state.textContent });
    this.setState({toDoList: list});
  }

  deleteToDo(i){
    let list = this.state.toDoList;
    list.splice(i, 1);
    this.setState({toDoList: list});
  }

  render(){
    const domList = this.state.toDoList.map((m, i) =>{
      return <li key={i}>
        タイトル:{m.title}<br/>
        内容:{m.content}<br/>
        <button onClick={e => this.deleteToDo(i)}>削除{i}</button>
      </li>;
    });

    return(
      <div>
        <div>

          タイトル:<input type="text" value={this.state.textTitle} 
            onChange={e => this.setState({textTitle: e.target.value})}/>

          内容:<input type="text" value={this.state.textContent} 
            onChange={e => this.setState({textContent: e.target.value})}/>

        </div>
        <div onClick={e => this.addToDo()}>追加</div>
        <ul>{domList}</ul>
      </div>
    );
  }
}

export default ToDoList;

8
4
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
8
4