Todo list

DEMO
Check off this task
Add new task
Look at code for this demo
Do stuff
TodoList.jsx

function TodoList() {
  const [todos, setTodos] = React.useState([
    { task: "Check off this task", isCompleted: false },
    { task: "Add new task", isCompleted: false },
    { task: "Do stuff", isCompleted: false },
  ]);
  const [newTodo, setNewTodo] = React.useState("");

  const addNewTodo = (e) => {
    e.preventDefault();
    if (newTodo === "") return;
    setTodos([...todos, { task: newTodo, isCompleted: false }]);
    setNewTodo("");
  };

  const completeTask = (task) => {
    // check off todo
    const newTodos = todos.map((item) => {
      if (task === item.task) item.isCompleted = !item.isCompleted;
      return item;
    });
    setTodos(newTodos);

    // make task disappear after a delay
    setTimeout(() => {
      setTodos((todos) => todos.filter((item) => item.task !== task));
    }, 1000);
  };

  return (
    <>
      <form onSubmit={addNewTodo}>
        <AddTodoCont>
          <Input
            value={newTodo}
            onChange={(e) => {
              setNewTodo(e.target.value);
            }}
            placeholder="Add todo..."
            style={{ width: "400px" }}
          />
          <UnstyledBtn>
            <AddTodoIcon />
          </UnstyledBtn>
        </AddTodoCont>
      </form>
      <TodoCont>
        {todos.map((todo) => (
          <TodoWrapper
            layout
            key={todo.task}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
          >
            <CheckboxWrapper
              onClick={() => {
                completeTask(todo.task);
              }}
            >
              {todo.isCompleted ? (
                <ImCheckboxChecked />
              ) : (
                <ImCheckboxUnchecked />
              )}
            </CheckboxWrapper>
            <TodoText isChecked={todo.isCompleted}>{todo.task}</TodoText>
          </TodoWrapper>
        ))}
      </TodoCont>
    </>
  );
}

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React