I am having a issue in trying to find and figure out a way to clear those checkboxes that are checked back into its original state(unchecked). I have a button known as "Clear Filter" that link to the const handleclear, It will allows me to perform two things:
1)To reset the filteredList data and return to its default value displayed(which i had already done)
2)To turn all the current checked checkboxes into unchecked( i tried different way from different reference that i can find but i failed to achieve)
So may i know if there's a way to clear the checkboxes checked state using the button? As i am running out of idea to troubleshoot the issue
If you want React to manage the state of your inputs you want to use controlled components. With this pattern, React becomes the 'single source of truth' for the state of the input.
A simple controlled checkbox would look like this:
function ControlledCheckbox() {
const [checked, setChecked] = React.useState(false);
function handleChange() {
setChecked(!checked)
}
return <input type="checkbox" checked={checked} onChange={handleChange} />
}
In the current case where you are filtering data using checkboxes, the checked attribute can be set as a boolean which is true/false depending on whether the particular filter criterion represented by that checkbox is included in the user's chosen filter criteria.
const criteriaChoices = ['foo', 'bar', 'baz']
function App() {
const [criteria, setCriteria] = React.useState(['foo']);
const handleChange(e) {
const checkboxId = e.target.id
setCriteria(criteria.includes(checkboxId)
? criteria.filter(c => c !== checkboxId)
: [...criteria, checkboxId]
)
};
return criteriaChoices.map(choice => (
<label key={choice} for={choice}>
<input
id={choice}
type="checkbox"
checked={criteria.includes(choice)}
onChange={handleChange}
/>
{choice}
</label>
))
In the above, the first checkbox rendered will be ticked because the criteria in state includes 'foo'. The other two will be unticked to start with because 'bar' and 'baz' are not in the criteria in state.
The handleChange function adds/removes the clicked filter criterion depending on whether or not it is already in criteria. Note you don't need to check e.target.checked because React is in full control of the state on which the checkbox's checked attribute depends.
Once your components are controlled, you can reset the checkboxes easily by resetting the state on which the checked attribute depends. So in the above code, calling setCriteria([]) in a handleReset function would mean that criteria.includes(choice) is always false and therefore every checkbox would remain unchecked.
I took the liberty of distilling the essential elements of the issue from your code and put together a small example using Mui components on CodeSandbox.