Skip to content

Commit

Permalink
feat(utils/react): add some window-related utils
Browse files Browse the repository at this point in the history
  • Loading branch information
AAGaming00 committed Oct 5, 2024
1 parent 723e2ff commit 063dedb
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/utils/react/react.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react';
import { Ref, useState } from 'react';

// this shouldn't need to be redeclared but it does for some reason

Expand Down Expand Up @@ -150,3 +151,21 @@ export const findInReactTree = (node: any, filter: findInTreeFilter) =>
// Specialised findInTree for React nodes
walkable: ['props', 'children', 'child', 'sibling'],
});

/**
* Finds the parent window of a DOM element
*/
export function getParentWindow<WindowType = Window>(elem: HTMLElement | null): WindowType | null | undefined {
return elem?.ownerDocument?.defaultView as any;
}

/**
* React hook to find the host window of a component
* Pass the returned ref into a React element and window will be its host window.
* @returns [ref, window]
*/
export function useWindowRef<RefElementType extends HTMLElement, WindowType = Window>(): [Ref<RefElementType>, WindowType | null | undefined] {
const [win, setWin] = useState<WindowType | null | undefined>(null);

return [(elem) => setWin(getParentWindow<WindowType>(elem)), win];
}

0 comments on commit 063dedb

Please sign in to comment.