Jefree Sujit Jefree Sujit - 11 months ago 46
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) {
// logic here?

React Modal code:

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

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.

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download