Adding Tasks
In this section, we'll add the ability to add tasks to the list.
Let us add interactivity by letting the user add tasks to the list. We'll add a text input and a button. When the user clicks the button, we'll add the text from the input to the list of tasks.
Adding a Text Input and Button
First, add a text input and a button to the page. We'll add them just above the list of tasks.
Though this is good enough for now, we can and should make it more accessible by adding a label for the input and a htmlFor
attribute on the label that matches the id
of the input.
Now, clicking on the label will focus on the input.
Adding a Task
The Add button doesn't do anything yet. Let's add a click handler to it that will log to the console for now.
Let's capture the value of the input and log it to the console. One of the ways to do this in React is to use a state variable to track the value of the input.
We'll use the useState
hook to create a state variable and a setter function. We'll also add a value
attribute to the input and set it to the state variable. While we are at it, let's add an onChange
handler to the input to update the state variable. This input is now a controlled input.
Now, we can update the button click handler to log the value of the input.
Before we can even add tasks to the list, we have to update our current tasks
variable that holds our list of tasks to use state variables; otherwise, the list will not update when we add a task.
We can add a task to the list by updating the tasks
state variable. We'll update the state variable using the setTasks
setter function. We'll use the spread operator to create a new array with the new task added.
As discussed in the previous section, unique IDs are usually created by a database. In this project, we'll use the current time in milliseconds as the ID for each task.
Great, we are now able to add tasks to the list!
Our JSX code is getting a bit long, so let's separate the button's onClick
handler into its own function. The input's onChange
handler is acceptable for now.
Awesome, but there are a ton of things that can go wrong when a user adds a task. For example, the user can add an empty task.
This gives us a good opportunity to learn about Testing. We'll cover testing in the subsequent sections.
At this point, your code should be a good match to the branch of the repository: 3-adding-tasks