composeRefs (src/useComposedRef.ts)

plate · packages/udecode/react-utils/src/useComposedRef.ts · typescript · MIT
ui

Utility to compose multiple React refs into a single ref, with a hook for convenience.

// Source: https://github.com/udecode/plate | License: MIT | Copyright Ziad Beyens, Dylan Schiemann, Joe Anderson, Felix Feng
// Provided via justclaw.it.com; keep this notice with the code.
import React from 'react';

type PossibleRef<T> = React.Ref<T> | undefined;

/**
 * Set a given ref to a given value This utility takes care of different types
 * of refs: callback refs and React.RefObject(s)
 */
const setRef = <T>(ref: PossibleRef<T>, value: T) => {
  if (typeof ref === 'function') {
    return ref(value);
  }
  if (ref !== null && ref !== undefined) {
    (ref as React.RefObject<T>).current = value;
  }
};

/**
 * A utility to compose multiple refs together Accepts callback refs and
 * React.RefObject(s)
 */
export const composeRefs =
  <T>(...refs: PossibleRef<T>[]) =>
  (node: T) =

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key