Created
January 14, 2019 12:15
-
-
Save daniele-zurico/ca46a2aaba159e96062ac0f4711ec336 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, useRef } 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 TodoRef = () => { | |
const [todoList, dispatch] = useReducer(todoListReducer, []); | |
const todoInputRef = useRef<any>(""); | |
const todoAddHandler = () => { | |
const todoName = todoInputRef.current.value; | |
dispatch({ type: "ADD", value: todoName }); | |
}; | |
const todoRemoveHandler = (todoItem: string) => { | |
dispatch({ type: "REMOVE", value: todoItem }); | |
}; | |
return ( | |
<React.Fragment> | |
<input type="text" placeholder="Todo" ref={todoInputRef} /> | |
<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 TodoRef; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment