How to move current focus based on the data-testId in ReactJS with TypeScript.

To set the focus on an element with a specific ‘data-testid’ , we can use the ‘useEffect’ hook to find the element and then call its ‘focus’ method.

  • We are checking mainMenuElement ia an instance of ‘HTMLElement’ or not and it tells TypeScript that ‘mainMenuElement’ has the ‘focus’ method.
  • The ‘tabIndex=”0″ attribute is added to ensure that the ‘div’ can receive focus.

Leave a comment