I’m trying to build a basic app in react. I have a checkbox for each item in the table and once if it is checked, I want to delete that item. But for now, I was just checking the working of checkbox. But my onChange is not triggering the handler function.
I have added a console log to my handleOnChange
function, I can see it’s not getting logged which means my ‘onChange
‘ is not triggering the handler.
Here is my Table.js code:
import React, { useState, useEffect } from "react";
import axios from "axios";
function Table() {
const [items, setItems] = useState([]);
const [isChecked, setIsChecked] = useState([false]);
useEffect(() => {
const loadData = async () => {
await axios.get('http://localhost:9000/')
.then(function (res) {
setItems(res.data);
})
.catch(function (err) {
console.log(err);
});
}
loadData();
}, [items]);
const handleOnChange = (index,e) => {
e.preventDefault();
console.log("Change event triggered");
setIsChecked(prevState => {
const newState = [...prevState];
newState[index] = !newState[index];
return newState;
});
};
const ItemList = ({ items }) => {
const listItems = items.map((item) => (
<tr className="border border-slate-300">
<td>
<input type="checkbox" name="checkbox" checked={isChecked[item._id]} onChange={(e) => handleOnChange(item._id,e)} />
</td>
<td key={item.name}>
{item.name}
</td>
<td key={item.quantity}>
{item.quantity}
</td>
<td key={item.price}>
{item.price}
</td>
</tr>
));
return (
<>
{listItems}
</>
);
};
return (
<div className="grid grid-flow-col auto-rows-max max-w-full justify-center place-content-center">
<table className="table-auto">
<thead>
<tr>
<th className="border border-slate-300 ...">Checked</th>
<th className="border border-slate-300 ...">Items</th>
<th className="border border-slate-300 ...">Quantity</th>
<th className="border border-slate-300 ...">Price</th>
</tr>
</thead>
<tbody>
<ItemList items={items} />
</tbody>
</table>
</div>
);
}
export default Table;
2
Answers
the issue might be the
isChecked
and how you are managing thechecked
prop of your input. TheisChecked
array is initialized as an empty array with a single false value and you’re accessingisChecked[item._id]
to determine the checked status.Since the
isChecked
is initially[false]
and this will not change in your code,isChecked[item._id]
will beundefined
.You should
setIsChecked
when you’re fetching the data:Do not call
e.preventDefault()
inside theonChange
handler. It makes you have to press the input twice to toggle on/off.Also, try to make the row its own component.