REACT TO-DOリスト 作り方 簡単
srcフォルダ内にtodo.jsを作成。
あとは写すと完成。
src/todo.js
import React, { Component } from 'react';
export default class Todo extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
name: ''
};
}
onInput = (e) => {
this.setState({
name: e.target.value
});
}
addTodo = () => {
const { todos, name } = this.state;
this.setState({
todos: [...todos, name]
});
}
removeTodo = (index) => {
const { todos, name } = this.state;
this.setState({
todos: [...todos.slice(0, index), ...todos.slice(index + 1)]
});
}
render() {
const { todos } = this.state;
return (<div>
<input type="text" onInput={this.onInput} />
<button onClick={this.addTodo} >登録</button>
<ul>
{todos.map((todo, index) => <li key={index}>
{todo}
<button onClick={() => { this.removeTodo(index) }}>削除</button>
</li>)}
</ul>
</div>);
}
}
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
// import App from './App';
import App from './todo';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();