Improving component names in React Developer Tools

Esa-Matti Suuronen
HackerNoon.com
3 min readFeb 15, 2017

--

The React Developer Tools is awesome part of React.js developer experience when digging into unknown code bases — or your own after a while.

But sometimes it just fails and displays your component names as <Unknown>. Why? Let’s go through the different components types to see how the name is set on them and let’s examine why sometimes it’s not there. Finally we’ll see what can be done about it.

I’m assuming EcmaScript spec 2015 or later here.

Function Declarations

JavaScript has a simple reflection API for function names

Classes

As you might know JavaScript classes are just syntax for the prototypal inheritance which means that classes are just functions. So the function reflection API works here too

Arrow Function Expressions

This works as expected too. The name is inferred from the variable declaration by the JavaScript engine

React.createClass()

In this case there is nothing JavaScript engines can do. Luckily the babel-plugin-transform-react-display-name of the Babel React preset steps in here and transpiles the variable name into a displayName property of the component

Failures

When you generate components dynamically like

Button.name and Button.displayName will be empty because in this case the name cannot be inferred by the JavaScript engine or the Babel plugin. They don’t know that the simple() function returns a React component.

Custom names

To help out this situation you can set the displayName property manually. On function components the devtools will prefer the name on the displayName property over the name property if both are set.

But this way you can get at best names like

Inspired by the display name transform plugin I created an additional display name Babel plugin:

babel-plugin-display-name-custom

With it you can configure which functions in your project create new React components and have the display names automatically inferred for them.

It would transpile the above example to

Checkout the Github page for more information

https://github.com/epeli/babel-plugin-display-name-custom

P.S.

If you like the above API style of the simple() example — checkout react-simple on Github for a production implementation of it for the web and React Native. The Babel plugin was initially created as part of it.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

--

--