Performance: Select bindings
This affects how quickly the UI updates when a user selects an option and how efficiently the DOM reflects the selected value.
let selected; <select bind:value={selected}> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select>
let selected; function handleChange(event) { selected = event.target.value; } <select on:change={handleChange}> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual event handler for select change | Multiple event listeners | Triggers reflow on each change | Moderate paint cost | [X] Bad |
| Svelte bind:value on select | Single reactive update | Minimal reflows, only if layout changes | Low paint cost | [OK] Good |
bind:value directive do in a Svelte <select> element?bind:value usagebind:value directive connects the selected option's value to a variable in Svelte, so changes update the variable automatically.bind:value does not do.color to a <select> element in Svelte?bind:value={variable}.<select bind:value={color}> matches correct syntax. <select bind:color> uses incorrect binding name. <select value={color}> only sets value but does not bind. <select bind:select={color}> uses invalid binding name. <script>
let fruit = 'apple';
</script>
<select bind:value={fruit}>
<option value='apple'>Apple</option>
<option value='banana'>Banana</option>
<option value='cherry'>Cherry</option>
</select>
<p>Selected fruit: {fruit}</p>fruit is initialized to 'apple'.select binds its value to fruit, so the option with value 'apple' is selected initially, and the paragraph shows that value.<script> let choice; </script> <select bind:value=choice> <option value='1'>One</option> <option value='2'>Two</option> </select>
bind:value={choice}.<select> in Svelte that allows users to pick a fruit, but if the user selects "None", the bound variable should be set to null instead of the string "none". Which approach correctly achieves this?value={null} becomes "null" string, not JavaScript null.<select bind:value={fruit}> and in a reactive statement set fruit = null if fruit === 'none' uses a reactive statement to watch fruit and set it to null when the string 'none' is selected, correctly converting the value.<select bind:value={fruit}> with an <option value={null}>None</option> incorrectly tries to bind null directly as value. Use <select bind:value={fruit}> and set the option value to undefined for None uses undefined which becomes string. Use <select bind:value={fruit}> and convert fruit to null on form submit only delays conversion, not reactive.Pass the test and this pattern moves unknown