samedi 25 avril 2020

How to toggle checkbox value in React Hooks?

I have an input type checkbox as follow:

const [is_checked,set_is_checked]= useState(false);

const toggle_payment = () => {
    set_is_checked(!is_checked);
    console.log(is_checked);
}


return(
    <div>
        <input checked={is_checked}  onChange={toggle_value} type="checkbox"/>
    </div>
)

The problem

This seems to work fine, But when I console.log(is_checked) it looks like it prints the previous value. I tried both onChange and onClick but got the same result. What confuses me is that the checkbox is getting checked / unchecked each time I click on the box, but the console.log prints different value than what expected to print, like when I check the box with the mouse click, the box got checked but the console.log prints false




Aucun commentaire:

Enregistrer un commentaire