jeudi 2 septembre 2021

Easy way to access checkboxes in react. I have more than 20 checkboxes

I have a filter bar. Filters are selected through checkboxes. So for each type, there can be many checkboxes(30 maybe or more in total). Filters can be removed in two ways i.e. by "filter tags" or by "checkboxes". When I remove filters by using checking/unchecking checkboxes it works fine but how can I bind checkboxes to tags? So when I remove a filter by closing the tag (X) it also unchecks the checkbox? If I do it by "useRef()" hook then I have to make 30-40 useRefs. I am using Redux state for updating selected filters (an array of filters). Like "Filter bar" is a different component and the "Filter tags" are in a different component.

I try to do it by useRef here but it seems for each check box I need a separate useRef.

Filter Bar

<li className="box">
<input name="aerospace" type="checkbox" ref={filterName} onChange={setFilterHandler} className="check-box"/>
<lable>Aero Space</lable>
</li>
<li className="box">
<div>
<input name="cybersecurity" type="checkbox"  ref={filterName} onChange={setFilterHandler} className="check-box"/>
<lable>Cyber Security</lable>
</div>
</li>




const Filters =()=>{
const filterName = useRef('');
const dispatch =useDispatch();
const deletedFilter = useSelector(state => state.filter.removedFilter);

const setFilterHandler =(event)=>{
    const name= filterName.current.name;
    const check= filterName.current.checked;
    if(event.target.checked){        
        dispatch(filterActions.addFilter(event.target.name));
    }
    else{
        dispatch(filterActions.removeFilter(event.target.name));
    }
} 



Aucun commentaire:

Enregistrer un commentaire