Skip to content

Commit eb4e215

Browse files
committed
fix: focus popup when opened
fix #7
1 parent 08b810a commit eb4e215

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

src/core.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// @flow
2+
/* eslint-env browser */
23

34
import * as React from 'react'
45

@@ -62,6 +63,9 @@ export function createPopupState({
6263
if (!parentPopupState.isOpen) return
6364
parentPopupState._setChildPopupState(popupState)
6465
}
66+
if (typeof document === 'object' && document.activeElement) {
67+
document.activeElement.blur()
68+
}
6569
setState({
6670
anchorEl:
6771
eventOrAnchorEl && eventOrAnchorEl.currentTarget

src/hooks.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// @flow
2+
/* eslint-env browser */
23

34
import { useState, useRef, useEffect } from 'react'
45

@@ -42,6 +43,15 @@ export function usePopupState({
4243
},
4344
[]
4445
)
46+
useEffect(
47+
() => {
48+
if (popupId && typeof document === 'object') {
49+
const popup = document.getElementById(popupId)
50+
if (popup) popup.focus()
51+
}
52+
},
53+
[popupId, state.anchorEl]
54+
)
4555
const setState = (nextState: $Shape<CoreState>) => {
4656
if (isMounted.current) _setState({ ...state, ...nextState })
4757
}

src/index.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// @flow
2+
/* eslint-env browser */
23

34
import * as React from 'react'
45
import PropTypes from 'prop-types'
@@ -81,6 +82,19 @@ export default class PopupState extends React.Component<Props, CoreState> {
8182
if (this._mounted) this.setState(state)
8283
}
8384

85+
componentDidUpdate(prevProps: Props, prevState: CoreState) {
86+
const { popupId } = this.props
87+
if (
88+
popupId !== prevProps.popupId ||
89+
this.state.anchorEl !== prevState.anchorEl
90+
) {
91+
if (popupId && typeof document === 'object') {
92+
const popup = document.getElementById(popupId)
93+
if (popup) popup.focus()
94+
}
95+
}
96+
}
97+
8498
render(): React.Node | null {
8599
const { children, popupId, variant, parentPopupState } = this.props
86100

0 commit comments

Comments
 (0)