svelte icon indicating copy to clipboard operation
svelte copied to clipboard

<select> element has wrong initial value in SSR

Open dimfeld opened this issue 3 years ago • 7 comments

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

dimfeld avatar Jan 19 '22 07:01 dimfeld

REPL https://svelte.dev/repl/8cf99db4663c4071a939497570b9b21d?version=3.2.2 not working when javascript is disabled

xmlking avatar Jan 18 '23 02:01 xmlking

Still occurring in latest

MaximSagan avatar Jun 06 '23 23:06 MaximSagan

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

image

cdemi avatar Oct 25 '23 09:10 cdemi

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

khromov avatar Nov 10 '23 12:11 khromov