Skip to content

Instantly share code, notes, and snippets.

@Harshmakadia
Last active January 5, 2022 12:49
Show Gist options
  • Save Harshmakadia/5e4402c1919301516628bab581213a41 to your computer and use it in GitHub Desktop.
Save Harshmakadia/5e4402c1919301516628bab581213a41 to your computer and use it in GitHub Desktop.
One function to update multiple input state value
import React from "react";
function Form() {
const [state, setState] = React.useState({
firstName: "",
lastName: ""
})
// same function can be used to update multiple values in the state
const handleChange = (evt) => {
const value = evt.target.value;
setState({
...state,
[evt.target.name]: value
});
}
return (
<form>
<label>
First name
<input
type="text"
name="firstName"
value={state.firstName}
onChange={handleChange}
/>
</label>
<label>
Last name
<input
type="text"
name="lastName"
value={state.lastName}
onChange={handleChange}
/>
</label>
</form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment