Handling input values is something that we’ve to do often in our React components.
In this article, we’ll look at how to handle inputs with React hooks.
Using the useState Hook
To make an input’s value usable in our React component, we’ve to set the input value as a state’s value.
To do this, we can use the useState
hook.
For instance, we can write:
import React from "react";
export default function App() {
const [inputValue, setInputValue] = React.useState("");
const onChangeHandler = (event) => {
setInputValue(event.target.value);
};
return (
<div>
<input
type="text"
name="name"
onChange={onChangeHandler}
value={inputValue}
/>
<p>{inputValue}</p>
</div>
);
}
We call the useState
hook to return an array with the inputValue
state and the setInputValue
function to set the inputValue
state.
Then we define the onChangeHandler
function with the event
parameter that calls the setInputValue
to set the inputValue
state.
event.target.value
has the input value.
And then we add an input element and pass in the onChangeHandler
event handler and the inputValue
state into the onChange
and value
props respectively.
Then we show the inputValue
.
We set the value
prop to inputValue
so we’ll see what we typed into the input.
If we use inputs often, we may also want to put the input logic in a hook:
import React, { useState } from "react";
const useInput = ({ type }) => {
const [value, setValue] = useState("");
const input = (
<input
value={value}
onChange={(e) => setValue(e.target.value)}
type={type}
/>
);
return [value, input];
};
export default function App() {
const [username, userInput] = useInput({ type: "text" });
return (
<div>
{userInput}
<p>{username}</p>
</div>
);
}
We create the useInput
hook that takes an object with thew type
property so we can set the input type.
Then we call useInput
in App
to use it.
We put the userInput
component in the div and the username
, which has the input value.
The hook has the same logic as we have before.
So we see the inputted value rendered when we type into the input.
Conclusion
We can handle input values by calling a state setter function with the input value so we can use the input value in our component.