This content originally appeared on DEV Community and was authored by Minoosh
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>
);
}
This line does the magic:
const inputId = id || name || label?.toLowerCase().replace(/\s+/g, '-');
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.
This content originally appeared on DEV Community and was authored by Minoosh
Minoosh | Sciencx (2025-10-29T23:43:19+00:00) A Small Trick for Smarter, More Reliable Inputs in React. Retrieved from https://www.scien.cx/2025/10/29/a-small-trick-for-smarter-more-reliable-inputs-in-react/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.