0

i built a simple modal with React and works just fine. but when you hit tab after the submit button the focus goes to the next element outside of the modal.

to fix that I want to detect detect the tab keypress and compare the current focused input with the last one inside the modal.

const focusable = myRef?.current?.querySelectorAll(
  'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);

window.addEventListener('keydown', handleKey);  

const handleKey = (event) => {
  if (event.key === "Tab") {
    if (document.activeElement === focusable[focusable.length - 1]) {
      focusable[0].focus(); // this always put the focus on the first input not the firs button
    }
  }
}

but it never goes to the close button. tab goes to the first input field even if I do a console.log(focusable[0]) it returns the close button but focus is still in the wrong input

here´s a sandbox that shows the issue. https://codesandbox.io/s/practical-wildflower-ootgd?fontsize=14&hidenavigation=1&theme=dark

handsome
  • 2,335
  • 7
  • 45
  • 73
  • Does this answer your question? [Implement modal close on click outside](https://stackoverflow.com/questions/56322048/implement-modal-close-on-click-outside) – Agney Jan 30 '20 at 02:59
  • Not really. That’s to close the modal if you click outside. I’m looking for a way to trap the keyboard tab so you can only focus on elements within the modal – handsome Jan 30 '20 at 03:21
  • Or this? https://stackoverflow.com/q/14572084/867720 – FMCorz Jan 30 '20 at 03:24
  • Or this: https://github.com/davidtheclark/focus-trap – FMCorz Jan 30 '20 at 03:32

0 Answers0