ReactJS - React.Children.forEach - Can I get the child component name?
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 }) => <li>{name}</li>;
FirstChild.displayName = 'FirstChild';
const SecondChild = ({ name }) => <li>{name}</li>;
SecondChild.displayName = 'SecondChild';
class ThirdChild extends React.Component {
static displayName = 'ThirdChild';
render() {
return (
<li>{this.props.name}</li>
);
}
}
class Parent extends React.Component {
componentDidMount() {
React.Children.forEach(this.props.children, child => {
console.log('name =', child.type.displayName);
})
}
render() {
return (
<ul>{this.props.children}</ul>
);
}
}
class App extends React.Component {
render() {
return (
<Parent>
<FirstChild name='1st child value' />
<SecondChild name='2nd child value' />
<ThirdChild name='3rd child value' />
</Parent>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
If you're using Babel, you can use this Babel plugin to automatically set the displayName
, so that child.type.displayName
will equal the string of whatever you've named the component:
https://www.npmjs.com/package/babel-plugin-add-react-displayname
It's easy to install and use, just read the directions and make sure to add the plugin name add-react-displayname
to your plugins array in your .babelrc
file.