In order to destroy a task, we must operate on the App.js file, as this is where we manage the array of tasks. We'll create a new function destroyTask that takes a destroyedTaskId. Here, we'll then use the Array filter function to filter out any tasks that match the destroyed task ID. If we find a match, we return false, else return true- the filter function expects a truthy boolean to keep the item in the list. The result of our filter call is the remaining tasks that aren't destroyed.

Now that we've got the edit and destroy functions setup for the task, we'll circle back to the Add New task and add some polish there.

Your mission

Turn the task into an editable input on adding the new task. Add a new attribute on the task to note that it is new. When this new attribute is present, we'll use the same editing functionality we've already built. This will allow the user to click add task, and instantly be able to type in a new task name.

Menu
Lesson 18/20
import { useState } from "react";
import styled from "styled-components";
import Button, { IconButton } from "./Button";

const TaskName = styled.div``;

const TaskInput = styled.input``;

const TaskRow = styled.div`
  display: grid; 
  grid-template-columns: 1fr 100px; 
  gap: 5px; 
  margin: 10px 0px; 
  width: 100%;   
`;

const RowActions = styled.div`
  display: grid; 
  grid-template-columns: 1fr 1fr; 
  gap: 4px; 
`;

function Task({ task, onSave, onDestroy }) {
  const [editing, setEditing] = useState(false);
  const [name, setName] = useState(task.name);

  function saveEdit() {
    onSave({
      ...task,
      name,
    });
    setEditing(!editing);
  }

  function cancelEdit() {
    setName(task.name);
    setEditing(false);
  }

  function editName({ target: { value } }) {
    setName(value);
  }

  return (
    <TaskRow>
      {editing ? (
        <TaskInput placeholder={name} autoFocus onChange={editName} />
      ) : (
        <TaskName> {name} </TaskName>
      )}
      <RowActions>
        {editing ? (
          <>
            <Button onClick={saveEdit}> Save </Button>
            <Button onClick={cancelEdit}> Cancel </Button>
          </>
        ) : (
          <>
            <IconButton onClick={() => setEditing(true)}> ✏️ </IconButton>
            <IconButton onClick={() => onDestroy(task.id)}> 🗑️ </IconButton>
          </>
        )}
      </RowActions>
    </TaskRow>
  );
}

export default Task;