Skip to content

Instantly share code, notes, and snippets.

@moritzsalla
Last active September 15, 2023 15:02
Show Gist options
  • Save moritzsalla/cafaab21cfb83337666440d599e80579 to your computer and use it in GitHub Desktop.
Save moritzsalla/cafaab21cfb83337666440d599e80579 to your computer and use it in GitHub Desktop.
import { createContext } from "react";
import { useSafeContext } from "hooks/useSafeContext";
type RootElem = React.RefObject<HTMLElement>;
const RootElementContext = createContext<RootElem | undefined>(undefined);
RootElementContext.displayName = "RootElementContext";
type RootElementProviderProps = {
children: React.ReactNode;
root: RootElem;
};
/**
* Pass down and access the root element *ref* far down in your
* component tree.
* @param root The root element *ref*.
* @example
* ```tsx
* const ref = useRef<React.ElementRef<"header">>(null);
* return (
* <header ref={ref}>
* <RootRefProvider root={ref}>
* ...
* </RootRefProvider>
* </header>
* );
*
* // Access the root element *ref* in a child component.
* const rootElemRef = useRootElement();
* rootElemRef.current?.focus();
* ```
*/
const RootElementProvider = ({ root, children }: RootElementProviderProps) => {
return (
<RootElementContext.Provider value={root}>
{children}
</RootElementContext.Provider>
);
};
/**
* Access the root element *ref* of the navigation.
* @example
* ```tsx
* const rootElemRef = useRootElementRef();
* rootElemRef.current?.focus();
*```
*/
export const useRootElementRef = () => {
return useSafeContext(RootElementContext);
};
export default RootElementProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment