Created
January 10, 2019 16:07
-
-
Save daniele-zurico/dcfe43771bb3fec51189d40d009521b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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