-
What version of Next.js are you using?5.0.0 What version of Node.js are you using?14.17.5 What browser are you using?Chrome, Firefox What operating system are you using?Linux How are you deploying your application?next start Describe the BugWhen a checkbox is rendered serverside in the unchecked state, then it remains in the unchecked state clientside even though a rendering cycle is performed where it is checked. Consider a page in import * as React from 'react';
import { useState } from 'react';
import { useRouter } from 'next/router';
export default function TestCheckbox() {
const router = useRouter();
const ischecked = router.query.a == "true";
console.log(`rendering: ischecked ${ischecked}`);
const [checked, setChecked] = useState(ischecked);
const handleChange = (ev) => { setChecked(!checked); }
return (
<div>
<input type="checkbox"
checked={checked}
onChange={handleChange} />
</div>
);
} I now visit http://localhost:3000/min?a=true On the client side, I see
in the console, making me believe that the page was rehydrated and rendered with Yet, the checkbox remains unchecked. Expected BehaviorI would expect the checkbox to be checked when the page is cold-loaded via http://localhost:3000/min?a=true, despite having been rendered in the unchecked state on the server side due to the lack of query parameters available there. To ReproduceA self contained example is given above. Place it in the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, the default value of import * as React from 'react';
import { useState } from 'react';
import { useRouter } from 'next/router';
export default function TestCheckbox() {
const router = useRouter();
const [checked, setChecked] = useState(false);
const handleChange = (ev) => { setChecked(!checked); }
React.useEffect(() => {
if (router.query.a === "true") {
setChecked(true)
}
}, [router.query.a])
return (
<div>
<input type="checkbox"
checked={checked}
onChange={handleChange} />
</div>
);
} |
Beta Was this translation helpful? Give feedback.
Hi, the default value of
useState
is not meant to be changed like that and should be updated viasetChecked
instead, moving the query value check inside of auseEffect
works properly e.g.