Skip to content

Commit

Permalink
fix: focus popup when opened
Browse files Browse the repository at this point in the history
fix #7
  • Loading branch information
jedwards1211 committed Mar 7, 2019
1 parent 08b810a commit eb4e215
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/core.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @flow
/* eslint-env browser */

import * as React from 'react'

Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/hooks.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @flow
/* eslint-env browser */

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

Expand Down Expand Up @@ -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<CoreState>) => {
if (isMounted.current) _setState({ ...state, ...nextState })
}
Expand Down
14 changes: 14 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @flow
/* eslint-env browser */

import * as React from 'react'
import PropTypes from 'prop-types'
Expand Down Expand Up @@ -81,6 +82,19 @@ export default class PopupState extends React.Component<Props, CoreState> {
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

Expand Down

0 comments on commit eb4e215

Please sign in to comment.