Let's assume that you want to create a modal that disappears on an outside click.
javascriptimport React, { useEffect, useState } from 'react' const Modal = () => { const [show, setShow] = useState(true) useEffect(() => { document.getElementById('Modal')?.focus() }, [show]) const handleBlur = (e) => { if (!event.currentTarget.contains(event.relatedTarget)){ setShow(false) } } return show ? <div id = 'Modal' onBlur = {handleBlur} tabindex = '1'> <p>This is a modal</p> <button>Dummy</button> </div> : null }
As the modal is a div, you need to add tabindex = '1'
to allow focusing. tabindex = '1'
and document.getElementById('Modal')
are for divs the equivalent of autoFocus
for input
elements.
Every time you show the modal, you refocus it.
When there is a blur event, check if the new target isn't part of the modal component. If it doesn't, you hide it.