Last active
January 5, 2022 12:49
-
-
Save Harshmakadia/5e4402c1919301516628bab581213a41 to your computer and use it in GitHub Desktop.
One function to update multiple input state value
This file contains 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