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
<scriptcontext="module">let counter = 0</script><script>exportlet label
let value
let eltId = 'input_'+ counter++
</script><div><labelfor={eltId}>{label}</label><div><inputid={eltId}bind:value></div></div>
App.svelte
<script>importInputfrom'./Input.svelte'</script><Inputlabel='Select Country' /><Inputlabel='Select Country' /><Inputlabel='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>exportlet name
exportlet label
let value
constgetInputId = () => {
return`input_${name}`
}
</script><div><labelfor={getInputId()}>{label}</label><div><inputid={getInputId()}bind:value></div></div>
And use it like:
App.svelte
<script>importInputfrom'./Input.svelte'</script><Inputname='country'label='Select Country' />
Checkout the REPL.
Post a Comment for "Svelte: Associate Label And Input In A Reusabe Way"