To cancel a task name edit, we'll create a new function cancelEdit. Here, we'll call setName to the original task name (task.name) and set editing to false. That's it. We don't need to update the parent component via onSave because we're not saving anything new on our task. We're simply reverting local state.

Your mission

Now let's hook up that garbage pail to delete a task. Using the strategies we've learned so far, how might you go about that?

Menu
Lesson 17/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 }) {
  const [editing, setEditing] = useState(false);
  const [name, setName] = useState(task.name);

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

  function cancelEdit() {
    // Set task name back to the original name
    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> 🗑️ </IconButton>
          </>
        )}
      </RowActions>
    </TaskRow>
  );
}

export default Task;