react-forward-ref-in-props
v2.0.0
Published
A TypeScript library for ref forwarding in React components, enabling ref to be passed as props with full type safety.
Downloads
445
Maintainers
Readme
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;