I need to loop through component's children
and do some things only if child component is of specific type:
React.Children.forEach(this.props.children, child => {
if (...) {
console.log('Suitable component!');
}
});
To check the data belongs to which data type there is an inbuilt javascript method called typeof. typeof can be used for validating the data type but there is one weird behavior of typeof Array that it gives us object as output.
Components serve the same purpose as JavaScript functions, but work individually to return JSX code as elements for our UI. Components usually come in two types, functional components and class components, but today we will also be talking about pure components and higher-order components.
Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console. The Components tab will show the current React component tree, along with any props, state, or context.
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 />');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With