I know this topic has been discussed many times and I have already tried a few things.
Initially the checkbox is not checked, which is correct. At the first click hasTableHeader
is still false
and only at the second click hasTableHeader
changes the state to true
, which is wrong, because the input then is unchecked. I would be very grateful for any hints.
import React, { useState } from 'react';
const [hasTableHeader, setHasTableHeader] = useState(false);
const handleHeaderChange = () => {
setHasTableHeader(!hasTableHeader)
}
return (
...
<input type="checkbox" checked={hasTableHeader} onChange={handleHeaderChange}/>
...
)
3
Answers
If you want to change state to opposite of current boolean state in react you can try :
Functional component
Class component
In your case the code you’re looking for here :
You can use this component anywhere like this :
works fine as react function component for me:
can then be used somewhere else like this:
<MyCheckBox/>
I think that your problem is somewhere else, because code is correct.