Svelte: Associate Label And Input In A Reusabe Way
I'm building a Svelte input component which should be usable multible times on the same page.
Solution 1:
You could define a counter in module context and then use it to create unique IDs
Input.svelte
<script context="module">
let counter = 0
</script>
<script>
export let label
let value
let eltId = 'input_'+ counter++
</script>
<div>
<label for={eltId}>{label}</label>
<div>
<input id={eltId} bind:value>
</div>
</div>
App.svelte
<script>
import Input from './Input.svelte'
</script>
<Input label='Select Country' />
<Input label='Select Country' />
<Input label='Select Country' />
See REPL
Solution 2:
Why not just define a unique name for the input since your need one? You could then just have a component like:
Input.svelte
<script>
export let name
export let label
let value
const getInputId = () => {
return `input_${name}`
}
</script>
<div>
<label for={getInputId()}>{label}</label>
<div>
<input id={getInputId()} bind:value>
</div>
</div>
And use it like:
App.svelte
<script>
import Input from './Input.svelte'
</script>
<Input name='country' label='Select Country' />
Checkout the REPL.
Post a Comment for "Svelte: Associate Label And Input In A Reusabe Way"