DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on

How to check if a component is a forward ref component in React?

In this article, we will review a code snippet from TipTap source code.

/**
 * Check if a component is a forward ref component.
 * @param Component
 * @returns {boolean}
 */
function isForwardRefComponent(Component: any) {
  return !!(
    typeof Component === 'object'
    && Component.$$typeof?.toString() === 'Symbol(react.forward_ref)'
  )
}
Enter fullscreen mode Exit fullscreen mode

This comment explains what this function does — isForwardRefComponent

Image description

You would write forwardRef in React using this below syntax:

import { forwardRef } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  // ...
});
Enter fullscreen mode Exit fullscreen mode

In React 19, forwardRef is no longer necessary. Pass ref as a prop instead. forwardRef will deprecated in a future release. Learn more here.

Read more about forwardRef.

Checking for forward_ref

typeof Component === 'object'
&& Component.$$typeof?.toString() === 'Symbol(react.forward_ref)'
Enter fullscreen mode Exit fullscreen mode

I don’t think you would find something like this in the documentation.

Few things I would like to mention here. If it were up to me, I would console.log the component that is created using forwardRef and then inspect its properties and find a reliable prop that I can check to ensure this component is a forward_ref. ’Symbol(react.forward_ref)’ this is likely a value of key — $$typeof

I used the docs example to log the MyInput component and it looks as shown below

Image description

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github — https://github.com/ramu-narasinga

My website — https://ramunarasinga.com

My Youtube channel — https://www.youtube.com/@thinkthroo

Learning platform — https://thinkthroo.com

Codebase Architecture — https://app.thinkthroo.com/architecture

Best practices — https://app.thinkthroo.com/best-practices

Production-grade projects — https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/ueberdosis/tiptap/blob/develop/packages/react/src/ReactRenderer.tsx#L25

  2. https://react.dev/reference/react/useRef

  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

Top comments (0)