react-forward-ref-in-props
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

react-forward-ref-in-props

A TypeScript library for ref forwarding in React components, enabling ref to be passed as props with full type safety.

Installation

npm install react-forward-ref-in-props

Usage

1. Create a Component

You can use the forwardRef utility function to create a component that accepts other props with a ref.

import { memo, ForwardedRef } from "react";
import forwardRef from "react-forward-ref-in-props"; // Import forwardRef

type MyComponentProps = {
  ref: ForwardedRef<HTMLInputElement | null>;
  color: string;
};

const MyComponent = memo(
  forwardRef(({ color, ref }: MyComponentProps) => {
    return (
      <>
        <div ref={ref}>{color}</div>
        <input type="text" ref={ref} />
      </>
    );
  })
);

export default MyComponent;

2. Use the Component with Ref

Now, you can use the MyComponent component and pass a ref to it.

import { useCallback, useRef } from "react";
import MyComponent from "./MyComponent";

const App = () => {
  const ref = useRef(null as HTMLInputElement | null);

  const onFocus = useCallback(() => {
    ref.current?.focus();
  }, []);

  return (
    <div>
      <button onClick={onFocus}>Focus on Input</button>
      <MyComponent color="orange" ref={ref} />
    </div>
  );
};

export default App;

Package Sidebar

Install

npm i react-forward-ref-in-props

Weekly Downloads

445

Version

2.0.0

License

MIT

Unpacked Size

8.48 kB

Total Files

13

Last publish

Collaborators

  • beenomjee