Reactjs - React.children.foreach - Can I Get The Child Component Name?
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 same behavior on
Solution 1:
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
.
constFirstChild = ({ name }) => <li>{name}</li>;
FirstChild.displayName = 'FirstChild';
constSecondChild = ({ name }) => <li>{name}</li>;
SecondChild.displayName = 'SecondChild';
classThirdChildextendsReact.Component {
static displayName = 'ThirdChild';
render() {
return (
<li>{this.props.name}</li>
);
}
}
classParentextendsReact.Component {
componentDidMount() {
React.Children.forEach(this.props.children, child => {
console.log('name =', child.type.displayName);
})
}
render() {
return (
<ul>{this.props.children}</ul>
);
}
}
classAppextendsReact.Component {
render() {
return (
<Parent><FirstChildname='1st child value' /><SecondChildname='2nd child value' /><ThirdChildname='3rd child value' /></Parent>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="app"></div>
Solution 2:
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.
Solution 3:
Use the es6 spread operator:
React.Children.forEach(children, child => {
const childType = { ...child.type }
console.log('child', childType.displayName)
})
Solution 4:
NOTE: Work only Development Mode
functionMyComponent() (
return<AnotherComponent />
)
// In React Function Component 👇functionAnotherComponent({children}) {
console.log(children.type.name) // result = 'MyComponent' return (<div></div>)
}
// In React Class Component 👇exportdefaultclassExtendsReact.Component {
console.log(this.children.type.name) // result = 'MyComponent' render() {
return (<div></div>)
}
}
Post a Comment for "Reactjs - React.children.foreach - Can I Get The Child Component Name?"