mercredi 9 février 2022

React controlled checkbox, attribute checked and chrome DevTools

I am learning how to work with multiple checkboxes in react. I use hook UseState. State is array of objects. When i click checkbox, state has changed and UI render fine. But when i open chrome dev tools checked attribute stay the same, whatever i click. Is it correct behavior?

const arr_resting_ru = [
    { id: "rest1", value: "Walking", isChecked: false },
    { id: "rest2", value: "Running", isChecked: true}
];

const [resting, setResting] = useState(arr_resting_ru);

const handlerCheckBoxRest=(id)=> {
    setResting((prevState)=>{

           return prevState.map((chbox)=>{
                if(chbox.id===id) return {...chbox, isChecked:!chbox.isChecked}
                else {return chbox;}
            })

        });
}

 <div className="rest-checkbox-create-profile">
                    <div className='text-under-custom-menu'>
                        Rest:
                    </div>

                    {resting.map((rest, index) => {
                        if(rest.isChecked===true) console.log(rest.value);
                        return <p key={index}>
                                <input type='checkbox' checked={rest.isChecked} 
                                onChange={()=>handlerCheckBoxRest(rest.id)} />
                                {rest.value}
                                </p>
                            
                        })
                    }

                </div>

In chrome dev tools attribute checked don't change, but state and UI is normal

All is fine when I set defaultChecked. But it is wrong way i think




Aucun commentaire:

Enregistrer un commentaire