Skip to content

Instantly share code, notes, and snippets.

@jimthoburn
Last active August 5, 2022 22:28
Show Gist options
  • Save jimthoburn/0cd92771663fd19174d6e44b91067b4f to your computer and use it in GitHub Desktop.
Save jimthoburn/0cd92771663fd19174d6e44b91067b4f to your computer and use it in GitHub Desktop.
Todo List
// import all of the things
const TodoList = (props) => {
const [todoList, setTodoList] = useState([]);
const [newTodo, setNewTodo] = useState("");
function updateNewTodo(event) {
setNewTodo(event.target.value);
};
function addNewTodo(event) {
setTodoList([
{
done: false,
text: newTodo,
},
...todoList,
]);
event.preventDefault();
};
function toggleTodo(todo) {
setTodoList(todoList.map(existingTodo => {
if (existingTodo === todo) {
return {
// flipped todo
...existingTodo,
done: !existingTodo.done,
};
}
return todo;
}));
};
function deleteTodo(todo) {
setTodoList(
todoList.filter(existingTodo => (existingTodo !== todo))
);
};
return (
<>
<h1>Todos App</h1>
<form onSubmit={addNewTodo}>
<h2>Add a todo</h2>
<label>
Enter your todo
<input type="text" value={newTodo} onChange={updateNewTodo} />
</label>
<button type="submit">Add TODO</button>
</form>
<section>
<h2>Todos</h2>
<ul>
{todoList.map(todo => {
return (
<li>
{todo}
<label>
<input type="checkbox" onChange={() => toggleTodo(todo)} />
Done
</label>
<button type="button" onClick={() => deleteTodo(todo)}>Delete</button>
</li>
);
})}
</ul>
</section>
</>
);
};
export TodoList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment