How to link a text input with associated error message in a reusable React component

Viewed 23

I have a React component called TextInput which looks like this:

const TextInput = React.forwardRef<HTMLInputElement, ITextInputProps>(
  ({ error, ...props }, ref) => {
    return (
        <>
            <input
                type="text" 
                aria-describedby="" //  see here
                ref={ref}
                {...props}
            />
            {error && (
                <p> //  how can I reference this?
                    {error}
                </p>
            )}
        </>
    )}
)

For accessibility, I am trying to link the error message to the field using aria-describedby.

In a normal HTML document I would just use the id of the paragraph tag, but with reusability in mind, I would like to learn how to do this in a React-like way.

The use of refs comes to mind, but I'm not sure how to apply it in this scenario.

1 Answers

I would say that the best way to do this is to create a required prop that handles the ID and you apply that ID on the aria fields.

With that in mind, if what you wanted is to generate the data dinamically you could use a useEffect running it only once and setting a state inside it.

function Component() {
  const [describedBy, setDescribedBy] = useState()

  useEffect(() => {
    setDescribedBy(generateRandomString());
  }, [])

  return (
    <div aria-describedby={describedBy}></div>
  )
}
Related