Trap focus in a React component

Trap focus with vanilla JavaScript

<div id="demo">
<button id="show">show modal</button>

<div id="modal">
Modal with <a href="#">with</a> <a href="#">some</a>
<a href="#">focusable</a> elements.

<button id="hide">hide modal</button>
import { createFocusTrap } from 'focus-trap'

const modal = document.getElementById('modal')

const focusTrap = createFocusTrap('#modal', {
onActivate: function () {
modal.className = 'trap is-visible'
onDeactivate: function () {
modal.className = 'trap'

document.getElementById('show').addEventListener('click', function () {

document.getElementById('hide').addEventListener('click', function () {

Trap focus with React

import React from 'react'
import ReactDOM from 'react-dom'
import FocusTrap from 'focus-trap-react'

const Demo = () => {
const [showModal, setShowModal] = React.useState(false)

return (
<button onClick={() => setShowModal(true)}>show modal</button>

<FocusTrap active={showModal}>
<div id="modal">
Modal with <a href="#">with</a> <a href="#">some</a>{' '}
<a href="#">focusable</a> elements.
<button onClick={() => setShowModal(false)}>
hide modal

ReactDOM.render(<Demo />, document.getElementById('demo'))

Closing thoughts



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store