I'm trying to get values from all selected checkboxes and store them in useState. I was able to get value of the selected row in a table, but I can't store multiple selected values in state. My code is
import React, { useState } from "react";
export default function App() {
const data = [
{
id: "1",
name: "Jane",
lastName: "Doe",
age: "25"
},
{
id: "2",
name: "James",
lastName: "Doe",
age: "40"
},
{
id: "3",
name: "Alexa",
lastName: "Doe",
age: "27"
},
{
id: "4",
name: "Jane",
lastName: "Brown",
age: "40"
}
];
const [peopleInfo, setPeopleInfo] = useState([
{
id: "",
first: "",
last: "",
age: ""
}
]);
console.log(peopleInfo);
return (
<div className="App">
<table>
<tr>
{data.map((item) => {
return (
<div
key={item.id}
style={{
display: "flex",
width: "150px"
}}
>
<input
onChange={() => {
setPeopleInfo({
id: item.id,
first: item.first,
last: item.last,
age: item.age
});
}}
value={peopleInfo}
style={{ margin: "20px" }}
type="checkbox"
/>
<td style={{ margin: "20px" }}>{item.name}</td>
<td style={{ margin: "20px" }}>{item.lastName}</td>
<td style={{ margin: "20px" }}>{item.age}</td>
</div>
);
})}
</tr>
</table>
</div>
);
}
and Codesandbox
I'm able to get id, name, last name and age values of the selected row, but when I select new checkbox previous row's info gets updated with the new one. I can't seem to figure out how to store all values from multiple selected checkboxes. Any help and suggestions are greatly appreciated.