Looping this.props.children how do I test their type?

All we need is an easy explanation of the problem, so here it is.

In the following code snippet in a custom React component

React.Children.map(this.props.children), (child) => {
    if (predicate(child)) {
        // do stuff
    }
    else {
        // do other stuff
    }
}

predicate is a function that tests the child for certain properties or whatever. How can I write predicate to test what type of element a child is?

In the article, Send Props to Children in React you see the same pattern that I applied above, except his predicate function looks like child.type === RadioOption.type — this doesn’t work if I want to check against a type the child has inherited from.

In my case, I have StatelessModalchild may be one of several different components that extends StatelessModal.

When I know that child is one of the Modal components that extends StatelessModal, I find that neither predicate = (child) => child instanceof StatelessModal nor predicate = (child) => child.type instanceof StatelessModal work.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I played around in the console and figured out this works:

predicate = (child) => child.type.prototype instanceof StatelessModal

While the type property of a ReactElement seems to be undocumented, it is reasonable to note that here, child is a ReactElement, and child.type is a ComponentClass (you may also find it may be a string or StatelessComponent) — the ComponentClass is the class that defines the component; if the component was created through inheritance, the classes prototype chain includes the inherited type which is revealed by instanceof

Method 2

The answer accepted not work for me at all.

I’ve test several ways to check children type. The conclusion comes that:

predicate = (child) => child.type === StatelessModal

Worked for both class components and functional components in [email protected] and [email protected] in both develop and production env.

Further test cases in https://github.com/dancerphil/react-children-type

And https://dancerphil.github.io/react-children-type/ shows the conclusion of production build.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply