Skip to content

<select> element has wrong initial value in SSR #7160

Closed
@dimfeld

Description

@dimfeld

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions