Created
July 29, 2021 15:41
-
-
Save Ananthnbhat/6824f778d05a8f131f26b43b6cf0554c to your computer and use it in GitHub Desktop.
Handle multiple inputs with a single handler in react js
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 './App.css'; | |
import CustomForm from "./components/CustomForm"; | |
function App() { | |
return ( | |
<div className="App"> | |
<CustomForm /> | |
</div> | |
); | |
} | |
export default App; |
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, { useState } from 'react'; | |
const userDetails = { | |
firstName: '', | |
lastName: '', | |
email: '' | |
} | |
const CustomForm = () => { | |
const [inputVal, setUserDetails] = useState(userDetails); | |
const handleChange = (event) => { | |
setUserDetails({ | |
...inputVal, | |
[event.target.name]: event.target.value | |
}) | |
} | |
return ( | |
<div> | |
<form> | |
<label htmlFor="firstName">First Name: </label> | |
<input | |
label="First Name" | |
id="firstName" | |
name='firstName' | |
value={inputVal.firstName} | |
onChange={handleChange} | |
/><br /> | |
<label htmlFor="lastName">Last Name: </label> | |
<input | |
label="Last Name" | |
id="lastName" | |
name='lastName' | |
value={inputVal.lastName} | |
onChange={handleChange} | |
/> <br /> | |
<label htmlFor="email">Email: </label> | |
<input | |
label="Email" | |
id="email" | |
name='email' | |
value={inputVal.email} | |
onChange={handleChange} | |
/><br /> | |
</form> | |
<hr /> | |
<div> | |
<h1>First name is: {inputVal.firstName}</h1> | |
<h1>Last name is: {inputVal.lastName}</h1> | |
<h1>Email is: {inputVal.email}</h1> | |
</div> | |
</div> | |
); | |
} | |
export default CustomForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment