I'm building a Svelte input component which should be usable multible times on the same page.
<div>
<label>{label}</label>
<div>
<input bind:value>
<!-- some more elements -->
</div>
</div>
Trying to associate label and input I have the following problem:
- I can't use implicit association by changing the outer
<div>
to<label>
, since the input is not a direct child. - I can't use the labels
for
attribute, since reusing the element would create mutible identical ids.
Is there a way to create component instance unique ids (pre- or postfixed) in Svelte or is there another solution to this problem.
Or is the best solution to manually set a random string as id?
<script>
const id = random_string();
/* ... */
</script>
<div>
<label for={id}>{label}</label>
<div>
<input {id} bind:value>
<!-- some more elements -->
</div>
</div>