Accessibility on error message load in react

Viewed 48

I have a sign in form that when given incorrect credentials an error message pops up. I want this error message to be focused when loaded, that way the user can easily hear the message and then tab down to the fields. I am having trouble identifying the best solution to implement.

aria-live works perfectly in reading the error, but I would like if the error message also focused. What is best practice to read and focus the error message? Would it be to add a ref?

1 Answers

I'm not sure why you'd like to focus the error message since it's read out loud, it should be enough. Also it might be confusing to force focus, maybe the user is in the middle of something else - which is the benefit of using an aria-live "polite" value for instance. Additionally using both aria-live & auto focus may result in reading the error message twice, but this needs to be tested.

This being said, to focus a DOM element you need to use a ref. Create it with useRef and assign it to the element. If the element to focus is rather a React component, you might need forwardRef. If the element is non-focusable (like a div, a span or a paragraph) you will have to add a tabIndex={-1}. Call ref.current.focus() when you need to.

Using a negative value for tabIndex will make them temporarily focusable & will not break the natural focus order of the page.

Sources :

Related