Vue3 Fundamentals · Composition & Reuse

Stable ids with useId

useId

Stable ids with useId

A label only points at its input when both share an id. Hard-coding one works until the component is used twice, and then two inputs share an id and the label points at the wrong one.

useId generates an id that is unique per component instance and stable across renders. Bind it to both the label and the input:

<script setup>
import { useId } from 'vue';

const id = useId();
</script>

<template>
  <label :for="id">Name</label>
  <input :id="id" />
</template>

Every instance gets its own id, so two copies of the component never collide. The value is stable, so it does not change between renders and the association holds. Use it whenever an element needs an id it does not already have — labels, aria-labelledby, aria-describedby.

The Test mounts your component and reads the input's id, then checks the label's for matches it. The starter binds neither attribute, so the id is missing and the Test fails. Generate the id in App.vue and bind it to both.

Challenge

The label and input are not linked, so screen readers cannot connect them. Export an App component from App.vue that generates an id with useId() and binds it to the label's for and the input's id.

The Test reads the input's id and checks the label's for matches it. The starter binds neither attribute, so the id is missing and the Test fails. Generate and bind the id.

App.vue
<script setup>
const label = 'Name';
</script>

<template>
  <label>{{ label }}</label>
  <input />
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.