How to use forwardref in Typescript ?

How to use forwardref in Typescript ?

Ref forwarding is a technique to automatically passing ref through a component to one of its children. This is usable in the scenario like re usable component in ReactJs. So How to use Forwardref with Typescript setup ? let's have a look

Understanding forwardRef

In React, forwardRef allows you to create components that can forward refs to their children. Which is useful when you need to manipulate a child component's DOM node from a parent component.

What's the wrong with prop ?

You might say that why we need to use the concept called forwardRef , instead why can't we passed that ref as usual prop in react ?

To understand this first we need to understand what the ref is, well the ref is used to directly access DOM, element in context of React.js.

When it's comes to the react.js, most time we actually communicating with Virtual DOM, instead of actual DOM. That's how react is design because it's take too much performance cost to update DOM completely when small change happen.

To overcome this issue react use virtual DOM and react first update that virtual DOM, then its complete both virtual and actual DOM and then after do relevant update to actual DOM, instead of update whole DOM.

But if you need to work with DOM directly in React.js, you can use ref for that. In most cases we use to take value from input.

đź’ˇ
The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. - ReactJs Doc

But it the issue, if we have nested element that need to pass ref to it's children, We can't do it like we pass prop, React doesn't work on that way. That's where the forwardRef comes handy.

For a example, assume that you might want to focus an input field or trigger an animation for it's parent element then you need to use forwardRef to ensure that ref is forward to it's DOM.

Consider following very basic example of forwardRef without TypeScript:

import React, { forwardRef } from 'react';

const MyInput = forwardRef((props, ref) => (
  <input ref={ref} {...props} />
));

export default MyInput;

In this example, the MyInput component forwards its ref to the underlying <input> element, as the example above the ref is attached to the input element and you can use than you able to use that as following example.

import React, { useRef } from 'react';
import MyInput from './MyInput'; // make sure youimport from current directory

const ParentComponent = () => {
  const inputRef = useRef(null);

  const focusInput = () => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <MyInput ref={inputRef} type="text" placeholder="Type here..." />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
};

export default ParentComponent;

example of forward ref

according to given example the focusInput function is invoke when the focus input button is clicked and then it checked whether the clicked item is null if not it focus that input, here we have used forwardRef to achieve that.

if(inputRef.current) is used to ensure that the element is actually in the DOM, This is important because if inputRef.current were null or undefined and we call a method like focus would result in an error.

Using forwardRef with TypeScript

If you are willing to use forwardRef in TypeScript, you need to add type annotations in order to work properly with Typescript.

Here are the step by step breakdown that you need to follow.

Step 1: Import Necessary Modules

First, import the modules that are required from the simple application that we are gonna build, open your code editor and type following code, in order to import Ref and forwardRef .

import React, { forwardRef, Ref } from 'react';

Step 2: Define Prop Types

Define the props for your component. In this example we are gonna use input component and , We can define props like this:

interface MyInputProps {
  placeholder?: string;
  type?: string;
}

Step 3: Create the Component with forwardRef

Next, you need to create the component using forwardRef. In TypeScript you need to require specify the type of the ref and the props explicitly:

const MyInput = forwardRef<HTMLInputElement, MyInputProps>((props, ref) => (
  <input ref={ref} {...props} />
));

Step 4: Add Display Name (Optional)

If you adding a display name then we able to debug easier:

MyInput.displayName = 'MyInput';

Full Example

Here is the complete code we have done so far.

import React, { forwardRef, Ref } from 'react';

interface MyInputProps {
  placeholder?: string;
  type?: string;
}

const MyInput = forwardRef<HTMLInputElement, MyInputProps>((props, ref) => (
  <input ref={ref} {...props} />
));

MyInput.displayName = 'MyInput';

export default MyInput;

Using the forwardRef Component

To use the MyInput component in another component, you can create a ref and pass it to MyInput:

import React, { useRef } from 'react';
import MyInput from './MyInput';

const ParentComponent: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);

  const focusInput = () => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <MyInput ref={inputRef} placeholder="Enter text here" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
};

export default ParentComponent;

In this example, the ParentComponent creates a ref using useRef and passes it to the MyInput component. The focusInput function focuses the input field when the button is clicked.

Do not overuse refs. You should only use refs for imperative behaviors that you can’t express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.

source : https://react.dev/reference/react/forwardRef

Conclusion

As legacy react doc mention "Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child. " - Legacy react doc

When use forwardRef with TypeScript that allows you to create components that can pass refs down to their children, providing greater control over the DOM elements. In this article we have provided a code that ensure your components are type-safe and easy to use

Be reading the article we hope you got an idea about how to use Forwardref and now you can now leverage forwardRef in your TypeScript projects, making your React components more flexible and powerful.

Happy coding!