Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS checkbox TRUE/FALSE show object

I’m working in a form with ReactJS + MUI

I have a checkbox with Boolean TRUE/FALSE

<Checkbox
 id="status"
 name="status"
 onChange={(e) => onInputChange(e)}
/>

This is the function onInputChange

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [user, setUser] = useState({
            username: '',
            email: '',
            status: bool,
        });

 const onInputChange = (e) => {
        setUser({ ...user, [e.target.name]: e.target.value })
        console.log(user)
    }

On my console.log I’m getting an object rather than the value.

Would you explain me what I’m doing wrong here, please?

>Solution :

For checkbox you have to use checked property, like this:

You have to send type as an extra parameter from onchange function.

const [user, setUser] = useState({
        username: '',
        email: '',
        status: bool,
    });

const onInputChange = (e, type) => {
    if (type === 'checkbox') {
      setUser({ ...user, [e.target.name]: e.target.checked })
    } else {
      setUser({ ...user, [e.target.name]: e.target.value })
    }
    console.log(user)
}

<Checkbox
 id="status"
 name="status"
 onChange={(e) => onInputChange(e, 'checkbox')}
/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading