UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【React】ForwardRefExoticComponentについて

ReactのForwardRefExoticComponentというのを見かけたので調べた

ForwardRefExoticComponent は、React.forwardRef を使用して作成されたコンポーネントの型を表す

Reactコンポーネントでどのように使用されるか

React では、ForwardRefExoticComponent は主に、親コンポーネントが子コンポーネントの DOM ノードに直接アクセスできるようにするために使用される

これは、フォーカス、選択、またはアニメーションを管理する場合に特に便利

このインターフェースにより、必要に応じて DOM ノードへの直接アクセスを犠牲にすることなく、コンポーネントが構成可能かつ再利用可能であることが保証される

型の定義

interface ForwardRefExoticComponent<P> extends NamedExoticComponent<P> {
  defaultProps?: Partial<P> | undefined;
  propTypes?: WeakValidationMap<P> | undefined;
}

使い方の流れ

  1. React.forwardRef を使用して関数コンポーネントを作成する。
  2. refprops を受け取るように設計する。
  3. ForwardRefExoticComponent 型が自動的に適用される。

使用例

import React, { forwardRef, useRef } from 'react';

type ButtonProps = {
  label: string;
};

const CustomButton = forwardRef<HTMLButtonElement, ButtonProps>(
  ({ label }, ref) => {
    return <button ref={ref}>{label}</button>;
  }
);

const ParentComponent = () => {
  const buttonRef = useRef<HTMLButtonElement>(null);

  const handleClick = () => {
    if (buttonRef.current) {
      buttonRef.current.focus();
    }
  };

  return (
    <div>
      <CustomButton ref={buttonRef} label="Click Me" />
      <button onClick={handleClick}>Focus Button</button>
    </div>
  );
};
  • ForwardRefExoticComponent を直接使うことは少なく、forwardRef を使用すると内部で適用される
  • ref を使うことで DOM 要素や他のコンポーネントインスタンスにアクセスできる
  • 高度な型付けが可能で、PropsRef の型を明確にできる