Skip to content

Instantly share code, notes, and snippets.

@daniele-zurico
Created January 10, 2019 16:07
Show Gist options
  • Save daniele-zurico/dcfe43771bb3fec51189d40d009521b7 to your computer and use it in GitHub Desktop.
Save daniele-zurico/dcfe43771bb3fec51189d40d009521b7 to your computer and use it in GitHub Desktop.
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