We've now added local state onto task through the useState
hook. When clicking on the pencil icon next to each task, a new component TaskInput
will render, which is a styled.input
. Any html element can be styled with styled components, and we don't have any styles to add into the input just yet, but we can when we want to.
The useState
call gives us two variables (that we named, as a reminder, you can name these anything but its good to keep the convention variable
, setVariable
). In the Task rendering, we now start a javascript expression through brackets ({ ... }
). Inside here, we use a ternary operator to ask whether our editing
variable is truthy or not, which at the moment it is not.
Once you click on the pencil, the click handler will run a function that we define () => setEditing(!editing)
to call the setEditing
hook setter to the new variable. The new variable is set to the inverse of editing (!editing), so when it's false, it becomes true, and when it's true it becomes false!
The result of all this is that we can click on each pencil icon to turn the task name into an input, and click it again to turn it back into a name. Awesome.
One more thing. You can see we added a placeholder
prop on the input. Placeholder is an html attribute that sets the placeholder value of the input. So, when we click edit, we can see the faded placeholder value of what our task name currently is. This is to remind the user what they are editing. Nice touch, right?
Your mission
Let's improve the experience a bit more here. Add an autoFocus prop on the TaskInput to automatically focus the input so the user can just start typing right as they click edit.
Another mission for you:
When editing, instead of the edit button and the garbage button, show Save and Cancel buttons.
import { useState } from "react"; import styled from "styled-components"; import { 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({ name }) { const [editing, setEditing] = useState(false); return ( <TaskRow> {editing ? ( <TaskInput placeholder={name} /> ) : ( <TaskName> {name} </TaskName> )} <RowActions> <IconButton onClick={() => setEditing(!editing)}> ✏️ </IconButton> <IconButton> 🗑️ </IconButton> </RowActions> </TaskRow> ); } export default Task;