Rolanda
Rolanda

Reputation: 348

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

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?

Upvotes: 0

Views: 47

Answers (1)

Priyen Mehta
Priyen Mehta

Reputation: 1185

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

Upvotes: 1

Related Questions