React hook to autofocus on an element by a query selector
This file contains 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