React input autoFocus
We just added an autofocus
attribute on the TaskInput. You'll notice we didn't specify autoFocus={true}
, just specifying any attribute by itself will default it to true. Now, when a user clicks on the pencil, it will automatically focus the input so they can start typing. Try it out.
We also added a new conditional inside RowActions to check editing
. If editing, we will now show Save and Cancel buttons. Save will call a new function that we defined saveEdit
, which just sets our editing variable to false. We haven't saved the new input value yet, so that's next up. Additionally, cancel will set editing to false (and we won't want to save the value there).
Your mission
Write a function to track the name of the task inside the Task component. We'll need to figure how to capture changes in the input and save them in our app.
Hints: Use the onChange
prop in the input. And perhaps you'll want to use useState
again.
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({ name }) { const [editing, setEditing] = useState(false); function saveEdit() { setEditing(!editing); } return ( <TaskRow> {editing ? ( <TaskInput placeholder={name} autoFocus /> ) : ( <TaskName> {name} </TaskName> )} <RowActions> {editing ? ( <> <Button onClick={saveEdit}> Save </Button> <Button onClick={() => setEditing(false)}> Cancel </Button> </> ) : ( <> <IconButton onClick={() => setEditing(true)}> ✏️ </IconButton> <IconButton> 🗑️ </IconButton> </> )} </RowActions> </TaskRow> ); } export default Task;