I'm trying to control a checkbox by using the value property that is coming from tableData
. And by default the value is true
.
let newData = newRes.data.map((e) => {
return {
...e,
installmentChecked: true,
lateFeeChecked: true,
depositChecked: true,
collectionChecked: true,
};
});
setTableData(newData);
After I mapped the data, I return the input like this.
const { data, index } = props;
return(
...
<input
type="checkbox"
value={latefee}
checked={data?.lateFeeChecked}
onChange={() => onChangeCheckbox('lateFeeChecked', index,data?.lateFeeChecked)}
/>
...
And this how I handle the value of the object.
const onChangeCheckbox = (key, index,status) => {
tableData[index][key] = !tableData[index][key];
console.log(tableData[index][key], 'props key');
console.log(status, 'status');
};
The problem that I'm getting is, the checkbox won't change at all. When I click, the console says.
false 'props key'
true 'status'
Is there any problem with my code? Or maybe anyone could gimme a better way to handle a checkbox in React? Appreciate any kind of responses, thanks before.
CodePudding user response:
you need to let react know to rerender your component.
You need to use useState
hook to achieve that.
It looks like you have setTableData
it is not clear if that's connected to useState
by the code you shared.
If it is, you need to do this:
const onChangeCheckbox = (key, index,status) => {
setTableData({
...tableData,
[index][key]: !tableData[index][key],
});
};
CodePudding user response:
const { data, index } = props;
return(
...
<input
type="checkbox"
value={latefee ? ‘true’:’’}
checked={data?.lateFeeChecked ? ‘checked’ : ‘’}
onChange={() => onChangeCheckbox('lateFeeChecked', index,data?.lateFeeChecked)}
/>
You may try this, as sometimes html doesn’t understand boolean value provided in React, and in those cases we need to provide boolean value in string.