JAVASCRIPT

Generate Stable, Unique IDs for Accessibility with useId

Utilize React's useId hook to generate unique and stable IDs that are perfect for connecting labels to inputs or other accessibility attributes, preventing hydration mismatches.

import React, { useId, useState } from 'react';

function FormField({ label, type = 'text', placeholder }) {
  const id = useId(); // Generates a unique ID
  const [value, setValue] = useState('');

  return (
    <div style={{ marginBottom: '15px' }}>
      <label htmlFor={id} style={{ display: 'block', marginBottom: '5px' }}>
        {label}:
      </label>
      <input
        id={id}
        type={type}
        placeholder={placeholder}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        style={{ padding: '8px', border: '1px solid #ccc', borderRadius: '4px', width: '250px' }}
      />
    </div>
  );
}

function MyForm() {
  return (
    <div style={{ padding: '20px', border: '1px solid #eee', borderRadius: '8px' }}>
      <h2>Registration Form</h2>
      <FormField label="First Name" placeholder="Enter first name" />
      <FormField label="Email Address" type="email" placeholder="[email protected]" />
      <FormField label="Password" type="password" placeholder="Enter password" />
      <button style={{ padding: '10px 15px', backgroundColor: '#007bff', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>
        Submit
      </button>
    </div>
  );
}

// Usage example:
// function App() {
//   return <MyForm />;
// }
How it works: `useId` is a React Hook for generating unique IDs that can be passed to accessibility attributes. It ensures that the generated ID remains stable across renders and is consistent between server-side rendering (SSR) and client-side hydration, preventing mismatches. This is particularly useful for connecting `label` elements to their corresponding `input` fields using the `htmlFor` and `id` attributes, improving accessibility without manually managing IDs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs