diff --git a/src/core.js b/src/core.js index cefb56b..e4e88dd 100644 --- a/src/core.js +++ b/src/core.js @@ -1,4 +1,5 @@ // @flow +/* eslint-env browser */ import * as React from 'react' @@ -62,6 +63,9 @@ export function createPopupState({ if (!parentPopupState.isOpen) return parentPopupState._setChildPopupState(popupState) } + if (typeof document === 'object' && document.activeElement) { + document.activeElement.blur() + } setState({ anchorEl: eventOrAnchorEl && eventOrAnchorEl.currentTarget diff --git a/src/hooks.js b/src/hooks.js index d06cb4a..a33c687 100644 --- a/src/hooks.js +++ b/src/hooks.js @@ -1,4 +1,5 @@ // @flow +/* eslint-env browser */ import { useState, useRef, useEffect } from 'react' @@ -42,6 +43,15 @@ export function usePopupState({ }, [] ) + useEffect( + () => { + if (popupId && typeof document === 'object') { + const popup = document.getElementById(popupId) + if (popup) popup.focus() + } + }, + [popupId, state.anchorEl] + ) const setState = (nextState: $Shape) => { if (isMounted.current) _setState({ ...state, ...nextState }) } diff --git a/src/index.js b/src/index.js index f027e77..e3b0d6c 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,5 @@ // @flow +/* eslint-env browser */ import * as React from 'react' import PropTypes from 'prop-types' @@ -81,6 +82,19 @@ export default class PopupState extends React.Component { if (this._mounted) this.setState(state) } + componentDidUpdate(prevProps: Props, prevState: CoreState) { + const { popupId } = this.props + if ( + popupId !== prevProps.popupId || + this.state.anchorEl !== prevState.anchorEl + ) { + if (popupId && typeof document === 'object') { + const popup = document.getElementById(popupId) + if (popup) popup.focus() + } + } + } + render(): React.Node | null { const { children, popupId, variant, parentPopupState } = this.props