one of my application section allows users to select mu;tiple options by selecting individual checkboxes in React by populating the Item to checkboxes. I wrote a code to handle onChange of the check box to send the _id to backend API.
The problem I'm facing when clicking one checkbox all checkboxes are getting selected. I need the app to able to check one checkbox at a time and capture its key id.
my code is;
const fetchCategory = async () => {
fetch(`http://localhost:4000/api/v1/category`)
.then(response => response.json())
.then(response => {
console.log("response: ", response.categories);
if (response.success === true) {
setCategoryList(response.categories)
// setIsLoading(false)
} else {
alert(response.message)
}
},
(error) => {
alert('Fetch faied: ' + error)
})
}
const [checked, setChecked] = useState(false);
const chechboxClickHandler = (id, event) => {
setChecked(!checked)
console.log(event);
if (!checked) {
console.log(!checked);
console.log("category id: ", id);
}
}
return (
<div className="card">
<div className="card-body">
<div className="row">
{categoryList && categoryList.map(c => (
<React.Fragment>
<div className="col-md-3 d-flex align-items-center">
<div class="form-check card">
<img src={`http://localhost:4000/api/v1/category/icon/${c.icon}`} width="50" height="50" alt={c.icon} />
<input class="form-check-input" type="checkbox" name="exampleRadios" id="exampleRadios1" value="option1" checked={checked} onChange={(event) => chechboxClickHandler(c._id, event)} />
<label class="form-check-label" for="exampleRadios1">
{c.title}
</label>
</div>
</div>
</React.Fragment>
))}
</div>
</div>
</div>
)