In React class component we can use same event handlers to update state for multiple controlled components using event.target.name
As below
class App extends PureComponent {
constructor(props) {
super(props);
this.state = {
name: "",
address: "",
occupation: ""
};
this.handleEventChange = this.handleEventChange.bind(this);
}
//Same event handler for all the three input field
handleEventChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
render() {
const { name, address, occupation } = this.state;
return (
<>
<>
Name:{" "}
<input name="name" value={name} onChange={this.handleEventChange} />
</>
<>
Address:{" "}
<input
name="address"
value={address}
onChange={this.handleEventChange}
/>
</>
<>
Occupation:{" "}
<input
name="occupation"
value={occupation}
onChange={this.handleEventChange}
/>
</>
</>
);
}
}
But in react hooks we might not be able to use the above mentioned way if we are using different state for each of the controlled component using 'useState'
We can use the same state in hooks as well by using spread operator.
create an initialState object with the name of all the controlled component and initialise it to ourState using useState
As Below,
const initialState = {
name: "",
address: "",
occupation: ""
};
const [ourState, ourSetState] = useState(initialState);
We can use the spread operator to update the state using single event handler
As below,
function handleEventChange(event) {
ourSetState({ ...ourState, [event.target.name]: event.target.value });
}
Hope this article helps in reducing some lines of code
The full code for react hooks is below.
function App() {
//initial state for our common state
const initialState = {
name: "",
address: "",
occupation: ""
};
//initialise our state
const [ourState, ourSetState] = useState(initialState);
const { name, address, occupation } = ourState;
//common event handler for all the controlled components.
//using spread operator to update the state
function handleEventChange(event) {
ourSetState({ ...ourState, [event.target.name]: event.target.value });
}
return (
<>
<>
Name: <input name="name" value={name} onChange={handleEventChange} />
</>
<>
Address:{" "}
<input name="address" value={address} onChange={handleEventChange} />
</>
<>
Occupation:{" "}
<input
name="occupation"
value={occupation}
onChange={handleEventChange}
/>
</>
</>
);
}
Happy Javascripting !!!
Top comments (4)
Great post saket 👌🏻
Cool 👍
Good job 👌🏻
Great post Saket ✌🏻😇👏🏽