Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useRef doesn't focus on modal

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading