Hi,
This is my Second smallest possible article.
Pardon me for mistakes and improvement is highly welcomed.
We will learn how we can store multiple values in single state using useState hook in functional component.
demo
Step 1: import useState and set initial values
initial values will be an object.
import "./styles.css";
import { useState } from "react";
export default function App() {
const initialvalues = {
fname: "",
lname: ""
};
const [data, setData] = useState(initialvalues);
return (
<div className="App">
</div>
);
}
Step 2: add two input box
values of input box will be data.fname data.lname, we will also assign name and id along with placeholder.
import "./styles.css";
import { useState } from "react";
export default function App() {
const initialvalues = {
fname: "",
lname: ""
};
const [data, setData] = useState(initialvalues);
return (
<div className="App">
<input
placeholder="enter name"
value={data.fname}
name="fname"
id="fname"
/>
<input
placeholder="enter surname"
value={data.lname}
name="lname"
id="lname"
/>
</div>
);
}
Step 3: adding OnChange event to each input box
each input box will have onChange event, which will target to handleChange arrow function.
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
As we know data is an object, so we can replace data.fname and data.lname using spread operator and reassigning new values of fname and lname using { ...data, key:"new Value" }
in this way [e.target.name]: e.target.value
will make new key value pair that will replace the previous key value pair.
we will also add a button to print the values, we can use this button to submit values to our backend.
import "./styles.css";
import { useState } from "react";
export default function App() {
const initialvalues = {
fname: "",
lname: ""
};
const [data, setData] = useState(initialvalues);
const display = () => console.log(data);
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
return (
<div className="App">
<input
placeholder="enter name"
value={data.fname}
name="fname"
id="fname"
onChange={handleChange}
/>
<input
placeholder="enter surname"
value={data.lname}
name="lname"
id="lname"
onChange={handleChange}
/>
<button onClick={display}>click</button>
</div>
);
}
Demo->
demo
if you found this helpful, you can donate (8823011424@upi) me 1 rupee. It will encourage me to write more, believe me I want to write more, I am trying to save money for extra monitor as my 14 inch laptop is not good enough.
Thank you!!
Top comments (0)