Implement a Todo list with useReducer.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
import React, { useReducer, useState } from 'react';
const initialState = [];
function reducer(state, action) {
switch (action.type) {
case 'add':
return [...state, { id: Date.now(), text: action.payload, completed: false }];
case 'toggle':
return state.map(todo =>
todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo
);
case 'delete':
return state.filter(todo => todo.id !== action.payload);
default:
throw new Error();
}
}
function TodoApp() {
const [state, dispatch] = useReducer(reducer, initialState);
const [text, setText] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
dispatch({ type: 'add', payload: text });
setText('');
};
return (
<>
<form onSubmit={handleSubmit}>
<input value={text} onChange={(e) => setText(e.target.value)} />
</form>
<ul>
{state.map((todo) => (
<li
key={todo.id}
style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
onClick={() => dispatch({ type: 'toggle', payload: todo.id })}
>
{todo.text}
<button onClick={(e) => { e.stopPropagation(); dispatch({ type: 'delete', payload: todo.id }); }}>Delete</button>
</li>
))}
</ul>
</>
);
}
export default TodoApp;