Skip to content

Instantly share code, notes, and snippets.

@daniele-zurico
Created January 14, 2019 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniele-zurico/ca46a2aaba159e96062ac0f4711ec336 to your computer and use it in GitHub Desktop.
Save daniele-zurico/ca46a2aaba159e96062ac0f4711ec336 to your computer and use it in GitHub Desktop.
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