How to Add a TypeScript Type for Forwarded Refs in React?

The correct way to specify types for React.forwardRef is by using generics in the following way:

forwardRef<RefType, PropsType>((props, ref) => /* ... */);

Please note that the ordering of the generic parameters is the opposite of the ordering of the function parameters — you must first specify the ref type and then the props type.

For example, let's consider a simple <Button /> component like the following:

import React from 'react';

type ButtonProps = React.HTMLProps<HTMLInputElement>;

const Button = React.forwardRef<HTMLInputElement, ButtonProps>(
    (props, ref) => <input type="button" ref={ref} {...props} />
);

For completeness sake, you could for example, use this as a child component inside another component, like so:

const Foo = () => {
    const ref = React.useRef<HTMLInputElement | null>(null);

    React.useEffect(() => {
        console.log(ref?.current);
    });

    return <Button ref={ref} value="Foo" />;
};

export default Foo;

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.