LoginSignup
4
3

More than 1 year has passed since last update.

ReactのRefをTypeSafeに独自実装する際のまとめ

Posted at

タイプセーフにReactのRefを独自実装する際、毎回忘れて調べなおしているので覚書

import { forwardRef, ForwardRefRenderFunction, useImperativeHandle } from 'react';

export interface HogeElement {
  bar: string;
  buzz: () => void;
}

export interface HogeProps {
  bizz: string;
}

const HogeRefFunction: ForwardRefRenderFunction<HogeElement, HogeProps> = ({
  bizz,
}, ref)=> {
  useImperativeHandle(ref, () => {
    return {
      bar: '参照等',
      buzz: () => {
        // 処理群
      }
    }
  })
  return <div>{bizz}</div>;
}
export const Hoge = forwardRef(HogeRefFunction);

各種命名規則

  • HTMLライクにするため、文末にElementを記述 HogeElement
    • HTMLDivElement的な勢い
  • Propsを文末に記述

備考

RefFunctionとコンポーネントを命名しておき、無名化を防ぐ
最終的に型は求まるため、forwardRefでwrapすれば完成

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3