From the course: React Hooks

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Creating controlled components with useState

Creating controlled components with useState - React.js Tutorial

From the course: React Hooks

Start my 1-month free trial

Creating controlled components with useState

- [Instructor] Another way to handle inputs in a form is to use a controlled component. A controlled component means that you handle form inputs using state variables. So let's refactor our form component to make this work. Now here, instead of useRef, I want to use state. So it'll look like this sound and setSound equals useState and then this'll just be an empty string as its initial state. And then we'll say const color and setColor equals useState. And our initial state here will just be black. So it was zero zero, zero, zero, zero, zero. Now we can get rid of both uses of useRef and instead replace it with useState here. The next thing I need to do is let's adjust our component a little bit. So instead of ref sound it's going to be value sound. Instead of ref color, value color. Then we're going to add an on change event. This will take in E for the event and then we'll say setSound(e.target.value) Then we can use…

Contents