DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on

How to check if a component is a class component in React?

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

/**
 * Check if a component is a class component.
 * @param Component
 * @returns {boolean}
 */
function isClassComponent(Component: any) {
  return !!(
    typeof Component === 'function'
    && Component.prototype
    && Component.prototype.isReactComponent
  )
}
Enter fullscreen mode Exit fullscreen mode

The beauty lies in the comment explaining what this function does. isClassComponent function name is pretty self-explanatory. It checks if a Component is a class component.

Image description

You would write a class component in React using this below syntax:

import { Component } from "react";

class Editor extends Component {...}
Enter fullscreen mode Exit fullscreen mode

So what are these checks?

Checking component typeof

typeof Component === 'function'
Enter fullscreen mode Exit fullscreen mode

isReactComponent

&& Component.prototype
&& Component.prototype.isReactComponent
Enter fullscreen mode Exit fullscreen mode

isReactComponent decides if a component is a class component.

It is a common practice to use !! to return boolean value.

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#L8

Top comments (2)

Collapse
 
fyodorio profile image
Fyodor

The beauty lies in the comment explaining what this function does

That’s what JSDoc does to people 😅 I mean, you need to write something there, and there’s not much choices 🤣

this is the way

Collapse
 
ramunarasinga-11 profile image
Ramu Narasinga

haha, can be tough when you have self explanatory function and a short code snippet. Lol, like the meme!