Created
May 16, 2021 07:47
-
-
Save meglio/0a839474d03d2c7e6e168024705d8353 to your computer and use it in GitHub Desktop.
React hook to autofocus on an element by a query selector
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 {useEffect, useState} from "react"; | |
import trim from 'lodash/trim'; | |
export default function useAutofocus() { | |
const [querySelector, setQuerySelector] = useState(null); | |
// Either a non-empty string OR null | |
let normalizedQuerySelector = querySelector; | |
if (typeof normalizedQuerySelector === 'string') { | |
normalizedQuerySelector = trim(normalizedQuerySelector); | |
if (normalizedQuerySelector === '') { | |
normalizedQuerySelector = null; | |
} | |
} else { | |
normalizedQuerySelector = null; | |
} | |
useEffect(() => { | |
if (normalizedQuerySelector === null || !document) { | |
return; | |
} | |
const element = document.querySelector(normalizedQuerySelector); | |
if (!element) { | |
return; | |
} | |
element.focus(); | |
// Reset the query selector, so that the api user can call us with the same selector multiple times in a row | |
setQuerySelector(null); | |
}, [normalizedQuerySelector]); // Make this effect re-fire only when querySelector changes | |
return setQuerySelector; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment