Jefree Sujit Jefree Sujit - 2 months ago 9
CSS Question

React - Prevent focus going out of modal when tabbing

I have built a react modal on my own. When I press tab key while the modal is opened, the focus still goes to the background page. How to restrict the focus within the components inside the modal?

What should be the logic below?

onKeyPress (e) {
if (e.keyCode === 9) {
e.preventDefault();
// logic here?
}
}


React Modal code:

<ReactModal onKeyPress={this.onKeyPress} >
<input type="text"/>
<input type="text"/>
</ReactModal>

Answer Source

Well, you can do it using a focus trap. Check out this npm module for that. Merely wrap your which contains modal with a focus-trap like this.

    <FocusTrap
              focusTrapOptions={{
                ...
              }}
            >
              <div className="trap">
                <p>
                  Here is a focus trap
                  {' '}
                  <a href="#">with</a>
                  {' '}
                  <a href="#">some</a>
                  {' '}
                  <a href="#">focusable</a>
                  {' '}
                  parts.
                </p>
                <p>
                  <button onClick={this.someCallback}>
                    Click Me
                  </button>
                </p>
              </div>

</FocusTrap>

Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.

Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.