I have created a checkbox with the list of data in useState. Now I need to make the checkbox work as a radio button. what kind of logic I need to use to make a checkbox work as a radio button
import { useState } from "react";
const Checkbox = () => {
const [items, setItems] = useState([
{ id: 1, checked: false, item: "apple" },
{ id: 2, checked: false, item: "bananna" },
{ id: 3, checked: false, item: "cherry" },
{ id: 4, checked: false, item: "dragon fruit" }
]);
const handleCheck = (id) => {
const listItem = items.map((item) => item.id === id ? {...item, checked: !item.checked} : item)
setItems(listItem)
}
return(
<div>
<ul>
{
items.map((item) => (
<li key={item.id}>
<input
type="checkbox"
checked = {item.checked}
onChange = {() =>handleCheck(item.id)}
/>
<lable>{item.item}</lable>
</li>
))
}
</ul>
</div>
)
}
export default Checkbox;
CodePudding user response:
Just set all the other items' checked
properties to false:
const handleCheck = (id) => {
const listItem = items.map((item) =>
item.id === id
? { ...item, checked: !item.checked }
: { ...item, checked: false }
);
setItems(listItem);
};
Hope this helps.
CodePudding user response:
If you want to use this as radio button logic, like selecting only one check box at a time.
while setting true
for a particular checkbox, you can also set false
for rest of the checkboxes
const handleCheck = (id) => {
const listItem =
items.map((item) =>
item.id === id ? {...item, checked: !item.checked} : {...item, checked: false} )
setItems(listItem)
}
CodePudding user response:
A bit complicated since it's not a built-in functionality. In order to make the checkboxes work as radio buttons, you can modify the handleCheck function to uncheck all the other items when one item is checked.
Here's one way to do that:
const handleCheck = (id) => {
const listItem = items.map((item) => {
if (item.id === id) {
return {...item, checked: !item.checked};
} else {
return {...item, checked: false};
}
});
setItems(listItem);
}
This will uncheck all the other items whenever one item is checked, so that only one item can be selected at a time, like a radio button.
Of course, there's also the built-in
<input
type="radio"
checked={item.checked}
onChange={() => handleCheck(item.id)}
/>