DEV Community

Amiltonxavier
Amiltonxavier

Posted on

React checkbox, only select the first item when I click on the label no matter which label I click.

I'm using React.js for my frontend and I'm doing category filters, but for that I used checkbox to mark the category I want and label to show the name of the category, I look like the figure below.Now I made a change and passed the input id to label. What is happening is the following whenever I click for whatever label it just selects a first item to be shown. No matter what label I click on, it only selects the first option.

const [checked, setChecked] = useState([])

    const handleToggle = c => () => {
        //return thr first index or -1
        const currentCategoryId = checked.indexOf(c)
        const newCheckedCategoryId = [...checked]
        // if currently not currently in verified state> push
// otherwise pull / take off
        if(currentCategoryId === -1){
            newCheckedCategoryId.push(c)
        } else{
            newCheckedCategoryId.splice(currentCategoryId, 1)
        }


        setChecked(newCheckedCategoryId);
        setChecked(newCheckedCategoryId);
        handleFilters(newCheckedCategoryId)
    }

    return categories.map((c, i) => (
        <li key={i} className="list-group-item d-flex justify-content-between lh-condensed list-unstyled">
            <input 
                type="checkbox"
                className="form-check-input"
                onChange={handleToggle(c._id)}
                value={checked.indexOf(c._id === -1)}
                id="checkbox"
            />
            <label htmlFor="checkbox" className="form-check-label">{c.name}</label>
        </li>
        ));
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
anilsansak profile image
Yaşar Anıl Sansak •

Hi,

It seems like you are having some problems with your code and you came here for answers. However, I think posting this question on Stackoverflow might be more beneficial to you :)

stackoverflow.com/questions/tagged...

Keep coding