DEV Community

Minoosh
Minoosh

Posted on

A Small Trick for Smarter, More Reliable Inputs in React

Have you ever forgotten to add an id to an input and later realized your label doesn’t work? It’s a small mistake, but it breaks accessibility and can easily happen when you’re moving fast.
Here’s a quick way to make sure it never happens again.

export default function Input({ 
  label, 
  id, 
  name, 
  ...props 
}) {
  const inputId = id || name || label?.toLowerCase().replace(/\s+/g, '-');

  return (
    <div>
      {label && <label htmlFor={inputId}>{label}</label>}
      <input id={inputId} name={name} {...props} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This line does the magic:

const inputId = id || name || label?.toLowerCase().replace(/\s+/g, '-');
Enter fullscreen mode Exit fullscreen mode

It simply checks:
If an id exists, use it.
If not, use the name.
If neither exists, generate one from the label (e.g. "First Name" → "first-name").
So even if you forget the id, your input will still stay linked to its label... no broken accessibility, no silent bugs.
This pattern isn’t something all developers use, but it’s a clean habit that makes your components more reliable and professional. It’s small details like this that separate quick prototypes from solid, production-ready code.

Top comments (0)