How to access the class name of a React object in this.props.children

In the response rendering method, which has some child components in this.props.children. How can I get the name of a component (class) for each of them to distinguish between them?

React.Children.map(this.props.children, function(child){
    // how can I get the class name of a child or some other identifier
})
+4
source share
3 answers

I think you want child._currentElement.type.displayName, but I would be careful to use such internal components if you did not want to double check that they still function correctly in each update. I do not think there is a public api to get the component name.

+1
source

ES6 , function.name,

import React from 'react'

...

getNameOfChildrenClass() {
    const singleChild = React.children.only(this.props.children),
          childClass = child.type

    return childClass.name        
}

React.children

+4

Same as @Vaclav, but if you use a redux connection, you will get “Connect” as the name, which may cause problems. Here is my improved version:

let{ name, displayName=name } = child.type;
React.cloneElement(child, {
  ...
  key:displayName,
});
0
source

All Articles