ReactJS - React.Children.forEach - can I get the name of the child component?

I have a React component (15.5.4) with many children, some of which are HTML elements and some are other React components.

I use server rendering and need the same behavior on server and client. The customer will use the React manufacturing assembly.

I need to iterate over the children and identify the specific type of React component. So I first thought of iterating with React.Children.forEach() and looking for the component name.

 React.Children.forEach(this.props.children, child => { console.log('name =', child.name) }) 

It seems that child.name and child.displayName do not exist.

Now child.type exists and is either a string (for HTML elements), like "ul" , or a function (for React components).

When this is a function, I can use lodash/get like this const type = get(child, 'type.name', '') to get the name of the component. However , it seems that this only works on the server, and not in assembling the assembly on the client side, where it returns the string: "t" . It looks like the assembly for development uses my component name for this function, but the assembly assembly renames it to t() . Therefore, I cannot use child.type.name .

Like me:

  • Iterate over child components and identify a specific type of component.?
  • What works in both development and production of React builds.?
+5
source share
1 answer

You can set the component name in the displayName property. If you are using ES6 classes, you can set the static displayName property to the component class. Then you can 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> 
+4
source

All Articles