dimanche 19 février 2023

Laravel ReactJs cant check or uncheck checkboxes

I want to create an edit a from containing checkboxes. I have initial ids to auto-check the checkboxes. If I use attribute check on Input checkbox, I can't change the checked/unchecked UI.

This is my html:

{props.ids.map((val, key) => {
    return (
        <div key={key}>
            <div className="form-control">
                <label className="label cursor-pointer">
                    <input 
                        type="checkbox" 
                        name="ids"
                        checked={data.ids.includes(val.id)} 
                        className="checkbox"
                        id={val.id}
                        value={val.id}
                        onChange={(e) => handleChange(e)} 
                    />
                    <span className="label-text">{val.name} ({val.id})</span> 
                </label>
            </div>
        </div>
    )
})}

This is my handleChange function and useForm:

const { data, setData, patch, errors, processing, recentlySuccessful } = useForm({
    ids: initialIds,
});

const handleChange = (e) => {
    let tempArray = [];
    if (e.target.checked)
    {
        if (_.indexOf(data.ids, e.target.value) === -1)
        {
            tempArray = [...data.ids, e.target.value];
        } else {
            tempArray = [...data.ids];
        }
    } else {
        tempArray = data.ids.filter(val => val !== e.target.value)
    }


    setData(e.target.name, tempArray);
};

Seems check attribute on Input resulting I can't check/uncheck the UI even though the handleChange function is fired when I click the checkbox.

Am I missing something? Any idea how to fix this?




Aucun commentaire:

Enregistrer un commentaire