Last active
March 31, 2019 00:01
-
-
Save andrzejewsky/cea2d32232baf26d3df2e325ca267f87 to your computer and use it in GitHub Desktop.
Regular Todolist (without useContext and useReducer)
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, useCallback } from "react"; | |
import ReactDOM from "react-dom"; | |
import "./styles.css"; | |
const AddTodo = ({ onClickAdd }) => { | |
const [todo, setTodo] = useState({ name: "", checked: false }); | |
const handleChangeTodo = evt => { | |
setTodo({ name: evt.target.value, checked: false }); | |
}; | |
const handleAddClick = useCallback(() => { | |
if (todo) { | |
onClickAdd(todo); | |
setTodo({ name: "", checked: false }); | |
} | |
}); | |
return ( | |
<div className="add-form"> | |
<input onChange={handleChangeTodo} value={todo.name} type="text" /> | |
<button onClick={handleAddClick}>ADD</button> | |
</div> | |
); | |
}; | |
const Item = ({ children, checked, onCheck, onClickDelete }) => ( | |
<li> | |
<input type="checkbox" onChange={onCheck} checked={checked} /> | |
<span>{children}</span> | |
<button onClick={onClickDelete}>delete</button> | |
</li> | |
); | |
const TodoList = ({ children }) => { | |
const [todos, setTodos] = useState([]); | |
const handleAddTodo = todo => { | |
setTodos([...todos, todo]); | |
}; | |
const handleDelete = todo => { | |
setTodos(todos.filter(el => el.name !== todo.name)); | |
}; | |
const handleCheckTodo = todo => { | |
const checkedTodos = todos.map(el => ({ | |
...el, | |
checked: todo.name === el.name ? !el.checked : el.checked | |
})); | |
setTodos(checkedTodos); | |
}; | |
return ( | |
<div className="todo-list"> | |
<div className="title">TodoList</div> | |
<AddTodo onClickAdd={handleAddTodo} /> | |
<ul> | |
{todos.map(todo => ( | |
<Item | |
key={todo.name} | |
checked={todo.checked} | |
onCheck={() => handleCheckTodo(todo)} | |
onClickDelete={() => handleDelete(todo)} | |
> | |
{todo.name} | |
</Item> | |
))} | |
</ul> | |
</div> | |
); | |
}; | |
function App() { | |
return ( | |
<div className="App"> | |
<h1>TodoList example</h1> | |
<TodoList /> | |
</div> | |
); | |
} | |
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