From the course: React Hooks

Building a checkbox with useState - React.js Tutorial

From the course: React Hooks

Building a checkbox with useState

- [Instructor] Another way that we can take advantage of useState, is to use it in combination with inputs. Here, we're going to make the status of a checkbox, checked or unchecked, a state variable. So the first thing we want to do is let's get rid of our old code here. We'll get rid of that useState call. Then inside of this div, we're going to add an input. And the input is going to have a type and that type is checkbox. And then we also want create a state variable. So this time it's going to be checked and setChecked. We'll call useState, and then the initial state is going to be false. So now I can use the value of checked inside of this input. So I'll say that the value is checked. Let's also add a paragraph tag next to this, and we'll say, "If it's checked, then say checked, "otherwise display not checked." Okay. So at this point, it shows our initial state that's working as we expect it to, but we're still not seeing the actual click work. So what we can do is let's add an onChange event to our input. And the onchange is going to, as we saw before, it's going to call setChecked. And what we can pass in here is whatever the opposite of checked is. There we go. It's usually a good idea to look at whatever the value of this variable is, to check the checked variable, if you will, and then return the opposite. So this is just a little enhancement that we can make, not much of a change, but checked and unchecked are going to work as we click. So there we go. We've created a checkbox component and we're using the useState hook to help us keep track of the value of checked.

Contents