Let's say I have a JS component - I am using Vue.JS - with a checkbox and associated label in it:
<template>
<input id="field1" type="checkbox">
<label for="field1">
Some label
</label>
</template>
Now, since we designed components to be reusable, I want to use it in multiple places of my app, at the same time. Problem: the ID is duplicated, and clicking a checkbox's label checks another checkbox since they share the same ID.
How to solve this problem?
For now I am generating a random hex ID at component mount to generate unique ID values, but it feels way too hackish.
You don't need to use an id to connect a label and an input in this specific case.
This code below achieves the same result without using HTML id
<template>
<label>
<input type="checkbox">
Some label
</label>
</template
You need to dynamically assign IDs as prop using v-bind. This way, you will be able to set it manually each time you use your component.
Component
<template>
<div class="field">
<input v-bind:id="id" type="checkbox"/>
<label v-bind:for="id">{{ label }}</label>
</div>
</template>
<script>
export default {
name: 'checkbox',
props: {
id: {
type: String,
required: true
},
label: {
type: String,
required: true
}
}
}
</script>
<Checkbox id="field1" label="Some text"></Checkbox>
<Checkbox id="field2" label="Another text"></Checkbox>
<div class="field">
<input id="field1" type="checkbox">
<label for="field1">Some text</label>
</div>
<div class="field">
<input id="field2" type="checkbox">
<label for="field2">Another text</label>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With