Last active
April 25, 2019 04:30
-
-
Save timc1/c3f105c5f05c4ea7df5b4810b83ef9e6 to your computer and use it in GitHub Desktop.
Simple hook using React Context API to give control of the flow of focus.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
const FocusContext = React.createContext() | |
export function FocusProvider({ children }) { | |
const focusElement = React.useRef(null) | |
const cacheFocusElement = element => (focusElement.current = element) | |
const toggleFocus = () => { | |
if (focusElement.current) { | |
focusElement.current.focus() | |
} | |
} | |
return ( | |
<FocusContext.Provider | |
value={{ | |
cacheFocusElement, | |
toggleFocus, | |
}} | |
> | |
{children} | |
</FocusContext.Provider> | |
) | |
} | |
export default function useFocus() { | |
const { cacheFocusElement, toggleFocus } = React.useContext(FocusContext) | |
return { cacheFocusElement, toggleFocus } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple usage
Wrap outer component with FocusProvider
Now, where ever you want to control focus: