jeudi 12 décembre 2019

Reactjs -- making api request based on check/uncheck of checkbox not understanding properly

I have a piece of code in reactJS which will make api request based on check/uncheck in future. Right now its just pushing/removing categoryId based on check/uncheck of checkbox in an array.

The code is perfect and working fine but I am unable to understand the code in some place. Please help me understand it.

code::

import React, {useState, useEffect} from 'react';

const Checkbox = ({categories}) => {
    const [checked, setChecked] = useState([]);

    const handleToggle = c => () => {
        // returns the first index or -1
        const currentIndex = checked.indexOf(c);
        const newCheckedCategoryArray = [...checked];

        if(currentIndex === -1){
            //then push in default state or remove it if its already there.
            newCheckedCategoryArray.push(c);
        }
        else{
            newCheckedCategoryArray.splice(currentIndex, 1)
        }
        setChecked(newCheckedCategoryArray);
        console.log(newCheckedCategoryArray);
    }

    return categories.map((c, i) => (
        <li className="list-unstyled" key={i}>
            <input type="checkbox" value={checked.indexOf(c._id === -1)}
                className="form-check-input" onChange={handleToggle(c._id)}
                 />
            <label className="form-check-label">{c.name}</label>
        </li>
    ));

}
export default Checkbox;

The code which i am not understand is below:: what is the purpose of the logic on 'value' prop there.

 <input type="checkbox" value={checked.indexOf(c._id === -1)}
                className="form-check-input" onChange={handleToggle(c._id)}
                 />



Aucun commentaire:

Enregistrer un commentaire