Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import React, { useState, useReducer } from "react";
const todoListReducer = (
state: string[],
action: { type: string; value: string }
) => {
switch (action.type) {
case "ADD":
return [...state, action.value];
case "REMOVE":
return state.filter((todo: string) => todo !== action.value);
default:
return state;
}
};
const Todo = () => {
const [todoList, dispatch] = useReducer(todoListReducer, []);
const [todoName, setTodoName] = useState("");
const inputChangeHandler = (evt: React.ChangeEvent<HTMLInputElement>) => {
setTodoName(evt.target.value);
};
const todoAddHandler = () => {
dispatch({ type: "ADD", value: todoName });
};
const todoRemoveHandler = (todoItem: string) => {
dispatch({ type: "REMOVE", value: todoItem });
};
return (
<React.Fragment>
<input
type="text"
placeholder="Todo"
onChange={inputChangeHandler}
value={todoName}
/>
<button type="submit" onClick={todoAddHandler}>
Add
</button>
<ul>
{todoList.map((todo: string) => (
<ul key={todo} onClick={() => todoRemoveHandler(todo)}>
{todo}
</ul>
))}
</ul>
</React.Fragment>
);
};
export default Todo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.