Handling input values is something that we’ve to do often in our React app.
In this article, we’ll look at how we can handle inputs in our React components.
Handling Inputs
To handle inputs, we can write:
import { useState } from "react";
const initialState = {
username: "",
email: "",
password: ""
};
export default function App() {
const [{ username, email, password }, setState] = useState(initialState);
const onChange = (e) => {
const { name, value } = e.target;
setState((prevState) => ({ ...prevState, [name]: value }));
};
return (
<form>
<div>
<label>
Username:
<input value={username} name="username" onChange={onChange} />
</label>
</div>
<div>
<label>
Email:
<input value={email} name="email" onChange={onChange} />
</label>
</div>
<div>
<label>
Password:
<input
value={password}
name="password"
type="password"
onChange={onChange}
/>
</label>
</div>
<button>Submit</button>
</form>
);
}
We create a state with the useState
hook.
Its initial value is set to an object with the username
, email
, and password
properties.
Then we have the onChange
function to update the value of the state.
We call setState
with a callback to get the prevState
which is the state’s current value.
And we return a new object which is a copy of prevState
, but with the [name ]
dynamic property set to e.target.value
.
e.target.value
has the inputted value.
Below that, we have the inputs with the value
prop to set the input value of those input fields.
And the onChange
prop is set to the onChange
function which lets us update the state to what we want.
Conclusion
We can handle input values by getting the value that’s typed in with e.target.value
.
Then we can update the state object with the new value by making a copy of it and overwriting the property value we want with a callback in the state setter function.