svelte
svelte copied to clipboard
Svelte 5: radio input loses value after hydration with conditional "checked"
Describe the bug
I have a simple set of radio buttons to switch language. I want to have the current option checked by using a simple conditional.
<input id="lang_nl" type="radio" name="lang" value="nl" onchange={switchLang} checked={lang === "nl"}>
When the page is rendered server-side, it looks like this:
<input id="lang_nl" type="radio" name="lang" value="nl" checked>
However after hydration, the browser shows the element like this:
<input id="lang_nl" type="radio" name="lang">
Removing the condition statement checked={lang === "nl"} or setting it to a "boolean" value i.e. checked fixes the issue
Reproduction
Note: in SPA mode this doesn't actually reproduce the issue. You need to run this locally and perform a hard refresh on the page to reproduce the behaviour, as the issue may have something to do with hydration? Repl link
Logs
No response
System Info
Svelte 5.0.0-next.123
Severity
annoyance
I feel this is expected, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox, checked can be property/state, on server side to set it as a default property, this is added as a attribute but without any value, but on client this is state/property of the input, to set it as attribute this you can use setAttribute, so I think Svelte only set the property.
But you are right, attribute cum property having a static value and should be shown in the initial template
As pointed out this behavior is intended, because checked is used for the default value, and non-static values are not seen as default values.
What problem does this cause for you in practise?
I think I have not been clear enough in my issue description. The entire value="nl" attribute disappears, breaking the input. The server renders this attribute and in SPA mode (e.g. the repl link) the issue also does not occur.
Only when you refresh the page and svelte hydrates the server rendered html, the value="nl" attribute is gone, breaking the input.