
yusukeM
いろいろ書き直したので参考にしてみてください
import { useState } from 'react'
function App() {
const [id, setId] = useState(1)
const [todos, setTodos] = useState([])
const [comment, setComment] = useState('')
const [radio, setRadio] = useState('all')
const addTodo = () => {
if (comment === '') return
const todo = {
id,
comment,
complete: false,
}
setTodos([...todos, todo])
setComment('')
setId(id + 1)
}
const deleteTodo = (todoId) => {
const newTodos = todos.filter((todo) => todo.id !== todoId)
setTodos(newTodos)
}
const toggleTodo = (todoId) => {
const newTodos = todos.map((todo) => {
if (todo.id === todoId) {
todo.complete = !todo.complete
}
return todo
})
setTodos(newTodos)
}
const switchTodos = () => {
if (radio === 'complete') {
return todos.filter((todo) => todo.complete)
}
if (radio === 'incomplete') {
return todos.filter((todo) => !todo.complete)
}
return todos
}
return (
<div className="App-header">
<h1>TODOリスト</h1>
<form>
<label>
<input
type="radio"
value="all"
onChange={(e) => setRadio(e.target.value)}
checked={radio === 'all'}
/>
全て
</label>
<label>
<input
type="radio"
value="incomplete"
onChange={(e) => setRadio(e.target.value)}
checked={radio === 'incomplete'}
/>
作業中
</label>
<label>
<input
type="radio"
value="complete"
onChange={(e) => setRadio(e.target.value)}
checked={radio === 'complete'}
/>
完了
</label>
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
</tr>
</thead>
<tbody>
{switchTodos().map((todo) => {
return (
<tr key={todo.id}>
<td>{todo.id}</td>
<td>{todo.comment}</td>
<td>
<button onClick={() => toggleTodo(todo.id)}>
{todo.complete ? '完了' : '作業中'}
</button>
<button onClick={() => deleteTodo(todo.id)}>削除</button>
</td>
</tr>
)
})}
</tbody>
</table>
<div>
<h2>新規タスクの追加</h2>
<input
placeholder="Enter a new TODO"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
<button onClick={addTodo}>追加</button>
</div>
</div>
)
}
export default App