UNPKG

react-best-modal

Version:

Simple is best. Accessible out of the box, tiny api, bring your own styles.

39 lines (38 loc) 1.47 kB
import * as React from 'react'; import Portal from './Portal'; import FocusLock from 'react-focus-lock'; const ESC_KEY = 27; export default class BestModal extends React.Component { constructor() { super(...arguments); this.onKeyDown = (e) => { if (e.keyCode === ESC_KEY) { this.props.onRequestClose(e); } }; } componentDidMount() { document.addEventListener('keydown', this.onKeyDown); this.props.appRoot.setAttribute('aria-hidden', 'true'); this.previousFocusedElement = document.activeElement; } componentWillUnmount() { document.removeEventListener('keydown', this.onKeyDown); this.props.appRoot.removeAttribute('aria-hidden'); if (this.previousFocusedElement) { // Something inside <FocusLock /> is setting activeElement. // This overrides that behaviour. setTimeout(() => { if (this.previousFocusedElement) { this.previousFocusedElement.focus(); } }, 0); } } render() { const { children, onRequestClose, appRoot, disableFocusLock, ...props } = this.props; return (React.createElement(Portal, null, React.createElement("div", Object.assign({ "aria-modal": "true", role: "dialog" }, props), React.createElement(FocusLock, { disabled: disableFocusLock }, children)))); } }