EN
React - forwardRef with generic component in TypeScript
5
points
In this short article, we would like to show how to forward reference to the generic components in React using TypeScript.
Quick solution:
const MyForm = forwardRef(
<T extends unknown> (props: Props<T>, ref: Ref<HTMLFormElement>) => {
// some component body here ...
}
);
export default MyForm as <T extends unknown> (props: Props<T> & { ref: Ref<HTMLFormElement> }) => JSX.Element;
Practical example
MyForm.tsx
file:
import React, { FormEvent, forwardRef, ReactNode, Ref } from 'react';
type Props<T extends unknown> = {
data: T;
children: ReactNode;
onSubmit: (data: T) => void;
};
const MyForm = forwardRef(
<T extends unknown>({ data, children, onSubmit }: Props<T>, ref: Ref<HTMLFormElement>) => {
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
// onSubmit(...);
};
// some code here ...
return (
<form ref={ref} onSubmit={handleSubmit}>
{children}
</form>
);
}
);
export default MyForm as <T extends unknown>(props: Props<T> & { ref: Ref<HTMLFormElement> }) => JSX.Element;
App.tsx
file:
import React, { useRef } from 'react';
import MyForm from './MyForm';
const App = () => {
const formRef = useRef<HTMLFormElement>(null);
const handleSubmit = (data: number) => console.log(data);
return (
<MyForm<number> ref={formRef} data={5} onSubmit={handleSubmit}>
{/* some code here ... */}
</MyForm>
);
};
export default App;