<select> element has wrong initial value in SSR
Describe the bug
When using code like the following, the SSR output does not generate the selected attribute on the <option> corresponding to the value. This means that the initial displayed value is incorrect until hydration takes place.
The behavior is similar when just using value instead of bind:value. In that case SSR generates a value attribute on the select, but the browser doesn't honor it.
<script>
let theValue = 'def';
</script>
<select bind:value={theValue}>
<option>abc</option>
<option>def</option>
</select>
I've worked around this in my own project by writing this:
<select bind:value={theValue}>
<option selected={theValue === 'abc'}>abc</option>
<option selected={theValue === 'def'}>def</option>
</select>
Reproduction
See the JS output of https://svelte.dev/repl/39c922f259564703ba7b8adc83c256f1?version=3.46.2 with generate set to ssr.
Reproduced here for reference.
/* App.svelte generated by Svelte v3.46.2 */
import { create_ssr_component } from "svelte/internal";
const App = create_ssr_component(($$result, $$props, $$bindings, slots) => {
let theValue = "Def";
return `<select><option value="${"Abc"}">Abc</option><option value="${"Def"}">Def</option><option value="${"Ghi"}">Ghi</option></select>`;
});
export default App;
Logs
No response
System Info
Svelte REPL
Severity
annoyance
REPL https://svelte.dev/repl/8cf99db4663c4071a939497570b9b21d?version=3.2.2 not working when javascript is disabled
Still occurring in latest
Looks like this bug is still present in 4.2.2
When SSR is enabled. The option that should be selected during SSR generation is not selected
Here's a repro of what I think is the same issue in SvelteKit. Before selecting the bar value which is selected by default, the foo value is shown initially:
https://www.sveltelab.dev/935c64eqjh3sf3i