Skip to content

Instantly share code, notes, and snippets.

@meglio
Created May 16, 2021 07:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save meglio/0a839474d03d2c7e6e168024705d8353 to your computer and use it in GitHub Desktop.
React hook to autofocus on an element by a query selector
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