27839

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

Question:

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 the server and client. The client will be using the production build of React.

I need to iterate over the children and identify a specific type of React component. So my first thought was to iterate using React.Children.forEach() and look for the component name.

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

It seems child.name and child.displayName don't exist.

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

When it's a function, I can use lodash/get like this const type = get(child, 'type.name', '') to get the component name. <strong>However</strong>, this only seems to work on the server, not in the client side production build, where it returns a string: "t". It looks like the development build uses my component name for the function, but the production build renames it to t(). So I can't use child.type.name.

How do I:

<ol><li>Iterate over a components children and identify a specific type of component..?</li> <li>Which works in both the development and production React builds..?</li> </ol>

Answer1:

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.

<pre class="snippet-code-js lang-js prettyprint-override">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")); <pre class="snippet-code-html lang-html prettyprint-override"><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>

Answer2:

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:

<a href="https://www.npmjs.com/package/babel-plugin-add-react-displayname" rel="nofollow">https://www.npmjs.com/package/babel-plugin-add-react-displayname</a>

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.

Recommend

  • How to specify x-axis in List when using Mathematicia and ListPlot?
  • How to catch a nested exception in java
  • assert in constexpr function
  • X86 64-bits Assembly Linux 'Hello World' linking issue
  • You do not have permission to use the bulk load statement error
  • Xamarin Forms HttpClient PostAsync does not return response
  • log insertions/updates/deletions in oracle database
  • How to investigate and optimise a slow MySQL query?
  • Display a custom text if user has already bought the current product In Woocommerce
  • cordova edit-config not updating AndroidManifest.xml
  • Identify File Type in Java
  • Spring Mvc submit/delete checked (selected) records from table
  • MySQL - Filter records which date is biggest
  • Firebase suddenly reports invalid signature
  • Detect when MathJax has finished loading in UIWebView
  • Identifying dates in strings using NLTK
  • Arc gradients in Flutter?
  • How to delete first 7 characters of folder name by using batch script?
  • When i select a Textfield the keyboard moves over it
  • read.table returning character matrix, would like numeric
  • Dynamically run java code with Process
  • Boolean filter using a timestamp value on a dataframe in Python
  • css: column-count 3, image floating spanning 2, chrome not playing. why?
  • Slice assignment to tensorflow variable
  • What does “T extends Junk” mean in a generic class in Java?
  • time column in sqlite using gorm
  • Year over Year Stats from a Crossfilter Dataset
  • Creating 2d platforms using JavaScript
  • How to write seo friendly url's using htaccess?
  • Is there a better way for handling SpatialPolygons that cross the antimeridian (date line)?
  • Neo4j…how to get a visual representation of my data?
  • Google App Engine Datastore: Dealing with eventual consistency
  • Unity3d lost directional light shadows after generate assetBundle (.unity3d file)
  • Apple Mach-O Linker error (“duplicate symbol”)
  • Sql - ON DUPLICATE KEY UPDATE
  • Firebase: How to read from external DB?
  • WPF custom control and direct content support
  • Create/delete users from text file using Bash script
  • Time Complexity of Fibonacci Algorithm [duplicate]
  • How to check if object is null in Java?