I have a simple list where in each li there is radio inputs to choose from.
Whenever I select an option, all the inputs in all the other elements are updating with the same option.
I included a unique id and a unique name as mentionned in React docs to regroup each group and make it separate but it didn't work.
I want to be able to select every element separately in the list. How to do so ?
https://codesandbox.io/s/affectionate-sun-i2khx?file=/src/App.js
import React, { useState } from "react";
export default () => {
const initialList = [
{
id: "1",
name: "John"
},
{
id: "2",
name: "Eric"
},
{
id: "3",
name: "Jonathan"
}
];
const handleChangeSelected = (event) => {
setSelected(event.target.value);
console.log(event);
};
const [list, setList] = useState(initialList);
const [Selected, setSelected] = useState("option1");
return (
<div>
<ul>
<div>
{list.map((item) => (
<li key={item.id}>
<div>
<div className="users">{item.name}</div>
<p />{" "}
<input
type="radio"
id={item.id}
name={item.id}
value="option1"
checked={Selected === "option1"}
onChange={handleChangeSelected}
/>
<label for="huey">Option 1</label>
</div>
<div>
<input
type="radio"
id={item.id}
name={item.id}
value="option2"
checked={Selected === "option2"}
onChange={handleChangeSelected}
/>
<label for="dewey">Option 2</label>
</div>
<div>
<input
type="radio"
id={item.id}
name={item.id}
value="option3"
checked={Selected === "option3"}
onChange={handleChangeSelected}
/>
<label for="louie">Option 3</label>
</div>
<br />
</li>
))}
</div>
</ul>
</div>
);
};
https://codesandbox.io/s/affectionate-sun-i2khx?file=/src/App.js
What I tried so far but didn't work to target the input to the corresponding id
function handleSelected(e, id) {
setSelected({
...Selected,
[id]: Selected[id]
});
}
selectedin each object of list array ?