Reputation: 173
The behaviour of a checkbox input is not being very reliable.
I'm setting the state of a checkbox based on state from the store. This works fine. However sometimes checking the checkbox will not fire the onchange
. Checking the box a second time will fire, however the UI will display the wrong state as it misfired the first time.
I'm using NextJS. This mostly happens when loading the page for the first time, or hard refresh.
import { useDispatch, useSelector } from 'react-redux';
import _cloneDeep from 'lodash/cloneDeep';
export default function Privacy() {
const consentObj = useSelector((state) => state.cookieOptions);
const dispatch = useDispatch();
const analyticsConsent = useSelector(
(state) => state.cookieOptions.analytics
);
function toggleConsentAnalytics() {
// this function will not fire on first input onchange
const newSettings = _cloneDeep(consentObj);
newSettings.analytics = !consentObj.analytics;
dispatch({ type: 'SET_COOKIE_OPTIONS', payload: newSettings });
}
return (
<div>
<div className={css.settingContainer}>
<strong>Analytics cookie</strong>
<label>
<div className={css.switchWrap}>
{analyticsConsent ? 'On' : 'Off'}
<span className={css.switch}>
<input
defaultChecked={analyticsConsent}
onChange={() => toggleConsentAnalytics()}
type="checkbox"
/>
<span className={css.slider}></span>
</span>
</div>
</label>
</div>
</div>
);
}
I've removed what I think is irrelevant code from my example.
I have an identical flow using a Class component and it works as expected. But it seems that we should be moving away from this into functional components so would very much like to solve this rather than revert to a Class!
Thanks in advance for any assistance
Upvotes: 1
Views: 6967
Reputation: 5091
You can use onClick
instead of onChange
and it will work properly.
This has nothing to do with react, but with how the onchange event works in html.
Upvotes: 7