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.
import React, { useEffect } from 'react';
const MainMenu = () => {
useEffect(() => {
// Locate the required element with data-testid
const mainMenuElement = document.querySelector('[data-testid="main-menu"]');
if(mainMenuElement && mainMenuElement instanceof HTMLElement) {
mainMenuElement.focus();
}
}, []);
return(
<div
data-testid="main-menu"
tabIndex="0" // Ensure the element can receive focus.
>
Main Menu content
<div>Other Content</div>
</div>
);
}
export default MainMenu;
- 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.