Skip to content

Commit

Permalink
fix: πŸ› correct useMeasure typings
Browse files Browse the repository at this point in the history
When upgrading to v15, I discovered some issues with `useMeasure` forcing me to downgrade to v14 again. Hopefully these changes fixes those issues...

* It was no longer possible to define the ref type, meaning components requiring a certain type of ref would reject it. Fixed this by making the function generic again.
* Previously you _had to_ define the ref type, while in v15 you _couldn't_. Fixed this by giving the generic type a default type of `HTMLElement`.
* The implicit typing of `useMeasureMock` combined with the ternary default export statement made the imported type of `useMeasure` very messy. Fixed this by making the type of `useMeasureMock` explicitly match `useMeasure`.
  • Loading branch information
Svish committed May 18, 2020
1 parent 12dfe49 commit bedbad7
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/useMeasure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ export type UseMeasureRect = Pick<
DOMRectReadOnly,
'x' | 'y' | 'top' | 'left' | 'right' | 'bottom' | 'height' | 'width'
>;
export type UseMeasureRef = (element: HTMLElement) => void;
export type UseMeasureResult = [UseMeasureRef, UseMeasureRect];
export type UseMeasureRef<E extends HTMLElement = HTMLElement> = (element: E) => void;
export type UseMeasureResult<E extends HTMLElement = HTMLElement> = [UseMeasureRef<E>, UseMeasureRect];

const defaultState: UseMeasureRect = {
x: 0,
Expand All @@ -20,8 +20,8 @@ const defaultState: UseMeasureRect = {
right: 0,
};

const useMeasure = (): UseMeasureResult => {
const [element, ref] = useState<HTMLElement | null>(null);
const useMeasure = <E extends HTMLElement = HTMLElement>(): UseMeasureResult<E> => {
const [element, ref] = useState<E | null>(null);
const [rect, setRect] = useState<UseMeasureRect>(defaultState);

const observer = useMemo(
Expand All @@ -46,6 +46,6 @@ const useMeasure = (): UseMeasureResult => {
return [ref, rect];
};

const useMeasureMock = () => [() => {}, defaultState];
const useMeasureMock: typeof useMeasure = () => [() => {}, defaultState];

export default (isClient && !!(window as any).ResizeObserver) ? useMeasure : useMeasureMock;

0 comments on commit bedbad7

Please sign in to comment.