Skip to content

Commit

Permalink
fix(types): [1016] updated type definition of useForkRef with generic…
Browse files Browse the repository at this point in the history
… suppor… (#1017)

* fix: [1016] updated type definition of useForkRef with generic support and null support

* fix: [1016] revert accidental code styling change

* fix: [1016] revert accidental code styling change

* chore(prettier): Update .prettierrc.json

Co-authored-by: Bhargav Ponnapalli <imbhargav5@gmail.com>
  • Loading branch information
neolivz and imbhargav5 committed Jun 30, 2022
1 parent 2680f37 commit add2bd5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
11 changes: 7 additions & 4 deletions src/hooks/useForkRef.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useMemo, MutableRefObject } from 'react';
import { useMemo } from 'react';
import type { HTMLElementOrNull, CallbackRef, AnyRef } from '../utils/utils';
/**
* Credit to material-ui for this snippet
*/

function setRef(ref: AnyRef, value: HTMLElementOrNull) {
function setRef<T extends HTMLElement | null>(ref: AnyRef<T> | null, value: T) {
if (typeof ref === 'function') {
ref(value);
} else if (ref) {
Expand All @@ -19,7 +19,10 @@ function setRef(ref: AnyRef, value: HTMLElementOrNull) {
* @param refA
* @param refB
*/
function useForkRef(refA: AnyRef, refB: AnyRef): CallbackRef | null {
function useForkRef<T extends HTMLElement | null = HTMLElementOrNull>(
refA: AnyRef<T> | null,
refB: AnyRef<T> | null
): CallbackRef<T> | null {
/**
* This will create a new function if the ref props change and are defined.
* This means react will call the old forkRef with `null` and the new forkRef
Expand All @@ -30,7 +33,7 @@ function useForkRef(refA: AnyRef, refB: AnyRef): CallbackRef | null {
return null;
}

return (refValue: HTMLElementOrNull) => {
return (refValue: T) => {
setRef(refA, refValue);
setRef(refB, refValue);
};
Expand Down
8 changes: 6 additions & 2 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@ import type { MutableRefObject } from 'react';

export type HTMLElementOrNull = HTMLElement | null;
export type RefElementOrNull<T> = T | null;
export type CallbackRef = (node: HTMLElementOrNull) => any;
export type AnyRef = CallbackRef | MutableRefObject<HTMLElementOrNull>;
export type CallbackRef<T extends HTMLElement | null = HTMLElementOrNull> = (
node: T
) => any;
export type AnyRef<T extends HTMLElement | null = HTMLElementOrNull> =
| CallbackRef<T>
| MutableRefObject<T>;

0 comments on commit add2bd5

Please sign in to comment.