Skip to content

Instantly share code, notes, and snippets.

@nmurzin
Forked from Harshmakadia/oneFunctionUpdater.js
Created September 17, 2020 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmurzin/97a799db962e92379ac8d93ff01d47be to your computer and use it in GitHub Desktop.
Save nmurzin/97a799db962e92379ac8d93ff01d47be 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