Articles → REACT.JS → Manage Multiple States Using A Single Object In React.Js
Manage Multiple States Using A Single Object In React.Js
Example
import ReactDOM from 'react-dom'
import { useState } from 'react';
const Home = () => {
const [userInput, setUserInput] = useState({
name: '',
email:''
})
const handleClick = () => {
alert(userInput.name + "***" + userInput.email) ;
}
const nameChangeHandler = (event) => {
setUserInput({
...userInput,
name : event.target.value,
});
}
const emailChangeHandler = (event) => {
setUserInput({
...userInput,
email: event.target.value,
});
}
return (
<form>
<div>
Name:
<p><input type="text" name="nameField" onChange={ nameChangeHandler}/></p>
Email:
<p><input type="text" name="emailField" onChange={emailChangeHandler}/></p>
<button onClick={handleClick}>Click me</button>
</div>
</form>
);
}
ReactDOM.render(<Home />, document.getElementById('root'));
Output
Click to Enlarge