I have a modal (popup) which sort of gallery. I’m trying to focus on the div by using useRef hook but it doen’t work as I expacted. I’m trying to create function that give me ability to switch images by pressing keyboard arrows. And it’s almost done. But now for switching images I’ve to click on whole modal for focusing on it. Without this keyboard doesn’t switch the images.
I found this code for auto focusing on modal DIV but it’s not work.
const ref = useRef(null);
useEffect(() => {
ref.current.focus();
}, []);
return(
<div
ref={ref}
tabIndex={1}
onKeyDown={(e) => handleKeyboardArrows(e)}>
<h1>My Popup</h1>
</div>
);
Guess someone explaing my mistakes and help me. Thx
>Solution :
useEffect hook with an empty dependency array will only run once when the component mounts, not when the modal is opened or closed. In your code, the focus method will only be called once, and it may not work if the modal is not visible or rendered at that time. To fix this, you need to use a dependency that reflects the modal state or props, such as modalOpen.
useEffect(() => {
if (modalOpen) {
modalRef.current.focus();
}
}, [modalOpen]);