Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate ID when using multiple instance of a container

Tags:

javascript

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.

like image 758
Mickaël Avatar asked Oct 24 '25 16:10

Mickaël


2 Answers

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
like image 92
Nishant Arora Avatar answered Oct 26 '25 05:10

Nishant Arora


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>

**Use case**
<Checkbox id="field1" label="Some text"></Checkbox>
<Checkbox id="field2" label="Another text"></Checkbox>

**Output**
<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>

[More about props.][1]
like image 42
Quentin Veron Avatar answered Oct 26 '25 04:10

Quentin Veron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!