I have a React (15.5.4) component with many children, some of which are HTML elements and some are other React components.
I\'m using server rendering and need the s
You can set the component's name in the property displayName
. If you're using ES6 classes, you can set a static property called displayName
into component's class. Then, you'll be able to get the child name with child.type.displayName
.
const FirstChild = ({ name }) => - {name}
;
FirstChild.displayName = 'FirstChild';
const SecondChild = ({ name }) => - {name}
;
SecondChild.displayName = 'SecondChild';
class ThirdChild extends React.Component {
static displayName = 'ThirdChild';
render() {
return (
- {this.props.name}
);
}
}
class Parent extends React.Component {
componentDidMount() {
React.Children.forEach(this.props.children, child => {
console.log('name =', child.type.displayName);
})
}
render() {
return (
{this.props.children}
);
}
}
class App extends React.Component {
render() {
return (
);
}
}
ReactDOM.render( , document.getElementById("app"));