Skip to content

Instantly share code, notes, and snippets.

@timc1
Last active April 27, 2019 23:57
Show Gist options
  • Select an option

  • Save timc1/5401146d8a7cb26c67addc4a5ca657d7 to your computer and use it in GitHub Desktop.

Select an option

Save timc1/5401146d8a7cb26c67addc4a5ca657d7 to your computer and use it in GitHub Desktop.
Simple hook to control of the flow of focus.
import React from "react"
export default function useFocus() {
const cachedElement = React.useRef(null)
const setFocusCache = () => (cachedElement.current = document.activeElement)
const setFocus = () =>
cachedElement.current ? cachedElement.current.focus() : {}
return { setFocusCache, setFocus }
@timc1

timc1 commented Apr 27, 2019

Copy link
Copy Markdown
Author

Usage

import useFocus from "./utils/focus-hook"

export default function App() {
  const { setFocusCache, setFocus } = useFocus()

  const initialRender = React.useRef(false)
  React.useEffect(() => {
    if (state.isDropdownShowing) {
      // When dropdown is open, cache the toggler.
      setFocusCache()
    } else {
      // Only trigger after the first render (useUpdatedEffect)
      if (!initialRender.current) {
        initialRender.current = true
        return 
      } 
      // Dropdown is now closed, set focus back to cached toggler.
      setFocus()
    }
  }, [state.isDropdownShowing, setFocus, setFocusCache])

  return // ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment