Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check type of React component

Tags:

reactjs

I need to loop through component's children and do some things only if child component is of specific type:

React.Children.forEach(this.props.children, child => {
    if (...) {
        console.log('Suitable component!');
    }
});
like image 208
Konstantin Smolyanin Avatar asked Apr 17 '19 14:04

Konstantin Smolyanin


People also ask

How do you check type in React?

To check the data belongs to which data type there is an inbuilt javascript method called typeof. typeof can be used for validating the data type but there is one weird behavior of typeof Array that it gives us object as output.

What is the type of a react component?

Components serve the same purpose as JavaScript functions, but work individually to return JSX code as elements for our UI. Components usually come in two types, functional components and class components, but today we will also be talking about pure components and higher-order components.

How do you identify the components of a react?

Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console. The Components tab will show the current React component tree, along with any props, state, or context.


3 Answers

This is what you should do:

import MyComponent from './MyComponent';

this.props.children.forEach(child => {
    if (child.type === MyComponent) {
        console.log('This child is <MyComponent />');
    }
});
like image 60
Ertan Hasani Avatar answered Oct 18 '22 03:10

Ertan Hasani


As pointed out by Konstantin Smolyanin, the accepted answer might not play nicely with react-hot-loader.

A safer alternative, suggested here:

import MyComponent from './MyComponent';
const myComponentType = (<MyComponent />).type;

this.props.children.forEach(child => {
    if (child.type === myComponentType ) {
        console.log('This child is <MyComponent />');
    }
});
like image 9
leonbloy Avatar answered Oct 18 '22 01:10

leonbloy


Other solution:

import MyComponent from './MyComponent';
// const myComponentType = (<MyComponent />).type;
// It's the same than
const myComponentType = React.createElement(MyComponent).type;

this.props.children.forEach(child => {
    if (child.type === myComponentType) {
        console.log('This child is <MyComponent />');
    }
});
like image 5
pacocom Avatar answered Oct 18 '22 02:10

pacocom