Created
May 1, 2019 21:56
-
-
Save andrzejewsky/2b37b699c49d95048108d6c79b229d1d to your computer and use it in GitHub Desktop.
This file contains hidden or 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, useContext } from "react"; | |
import ReactDOM from "react-dom"; | |
import "./styles.css"; | |
const reducer = (todos, action) => { | |
switch (action.type) { | |
case "ADD_TODO": | |
const newTodo = { id: todos.length + 1, name: action.payload }; | |
return [...todos, newTodo]; | |
case "REMOVE_TODO": | |
return todos.filter(el => el.id !== action.payload); | |
default: | |
return todos; | |
} | |
}; | |
const TodoContext = React.createContext(); | |
const Header = ({ children }) => { | |
const { todos } = useContext(TodoContext); | |
return ( | |
<h1> | |
{children} ({todos.length}) | |
</h1> | |
); | |
}; | |
const Input = () => { | |
const { methods } = useContext(TodoContext); | |
const [todo, setTodo] = useState(""); | |
const handleChange = evt => { | |
setTodo(evt.target.value); | |
}; | |
const handleAdd = () => { | |
methods.addTodo(todo); | |
setTodo(""); | |
}; | |
return ( | |
<div> | |
<input type="text" name="todo" value={todo} onChange={handleChange} /> | |
<button onClick={handleAdd}>Add</button> | |
</div> | |
); | |
}; | |
const Todo = ({ id, name }) => { | |
const { methods } = useContext(TodoContext); | |
return ( | |
<div> | |
{name} | |
<button onClick={() => methods.removeTodo(id)}>done</button> | |
</div> | |
); | |
}; | |
const TodoList = ({ name }) => { | |
const { todos } = useContext(TodoContext); | |
return ( | |
<div className="todolist"> | |
<Header>{name}</Header> | |
<Input /> | |
{todos.map(todo => ( | |
<Todo key={todo.id} name={todo.name} id={todo.id} /> | |
))} | |
</div> | |
); | |
}; | |
const TodoListContainer = ({ name }) => { | |
const [todos, dispatch] = useReducer(reducer, [ | |
{ id: 1, name: "milk" }, | |
{ id: 2, name: "beer" } | |
]); | |
const contextValue = { | |
todos, | |
methods: { | |
addTodo: todo => dispatch({ type: "ADD_TODO", payload: todo }), | |
removeTodo: id => dispatch({ type: "REMOVE_TODO", payload: id }) | |
} | |
}; | |
return ( | |
<TodoContext.Provider value={contextValue}> | |
<TodoList name={name} /> | |
</TodoContext.Provider> | |
); | |
}; | |
const App = () => <TodoListContainer name="Things to buy" />; | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment