-
-
Save nmurzin/97a799db962e92379ac8d93ff01d47be to your computer and use it in GitHub Desktop.
One function to update multiple input state value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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