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>
</div>
</div>
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 () {
focusTrap.activate()
})

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

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 (
<div>
<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
</button>
</div>
</FocusTrap>
</div>
)
}

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