Check type of React component
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 />');
}
});
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 />');
}
});
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 />');
}
});