Search code examples
javascript

Duplicate ID when using multiple instance of a container


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.


Solution

  • 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