sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
79.91k stars 4.25k forks source link

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

Open dimfeld opened 2 years ago

dimfeld commented 2 years ago

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

xmlking commented 1 year ago

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

MaximSagan commented 1 year ago

Still occurring in latest

cdemi commented 1 year ago

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

khromov commented 1 year ago

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

n0099 commented 3 weeks ago

https://github.com/nuxt/nuxt/issues/26734

nextlevelshit commented 1 week ago

Might be a bigger topic. Any thing new here?

dimfeld commented 1 week ago

No, this is present in Svelte 5 as well (REPL Link)

CleanShot 2024-11-05 at 10 14 18@2x