Home > database >  ReactJS checkbox TRUE/FALSE show object
ReactJS checkbox TRUE/FALSE show object

Time:12-29

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

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?

CodePudding user response:

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')}
/>
  • Related