Intro to Controlled Inputs With React Hooks
I recently built an app for my family and friends called Nalarama, and I was reminded of how useful controlled forms are. In my app, I ask users to make multiple guesses on my puppy’s mix of breeds, which requires multiple inputs. With controlled form inputs, the value typed into the input is easily accessible, and I was able to effortlessly use those values in HTTP
POST requests, and also in JSX elements wherever I deemed necessary.
This post will be a glimpse into controlled inputs, and will demonstrate what that looks like when using React Hooks.
First and foremost, when I was learning about controlled inputs, it was hammered into my brain that a controlled form has — “inputs which get their value from state” — and then we had to repeat that sentence like 10 times in a row.
The reason I think my teachers saw this necessary was because this is the principal concept behind controlled forms. As the input is being typed into, we will have a function which updates a state variable. The input will get it’s value from the updated state variable which is constantly changing with every keystroke. It is a very responsive, and “controllable” input, which comes in handy from time to time.
Let’s look at an example which attempts to demonstrate this as simply as possible:
This is a component I’ve appropriately named
ControlledInput which holds my “form”. Let’s briefly discuss what goes on inside of this component.
The important thing happening here is lines 8 through 13, the input. This is a
text input, and as you can see, it gets it’s
value from our state variable,
someValue. In the
onChange prop, we use
setSomeValue as a callback function to set
someValue to whatever has been typed every time it changes. We access that value through the event object:
Let’s see what this looks like in real time:
Here I have the React dev tools pulled up so you can see that every time a letter is typed, the state changes. This allows me to use that state to create an
<h2> element with
someValue inside it (inside the green box).
To clean up the
onChange prop, we can extract the function inside out to a handler, like so:
This gives us the same result, but having a handler looks better and cleans up the input props.
This has been a very quick intro to controlled forms using React Hooks, I hope it was beneficial to you to read it! Controlled inputs are a great way to have a variable which can access the value being typed into it quickly, and effortlessly.
As always, happy hacking!