Languages
[Edit]
EN

React - forwardRef with generic component in TypeScript

5 points
Created by:
Root-ssh
175020

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;

 

Alternative titles

  1. React - forwardRef on generic component in TypeScript
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - forwardRef with generic component in TypeScript
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join