how to set displayName in a functional component [React]

JavascriptReactjsFunctional Programming

Javascript Problem Overview


I know that setting the displayName is sometimes required especially when you're dealing with production builds. I want to know how to set it using my functional component - is it possible/allowed?

Here's what I've got in my class component:

const MyComponent = React.createClass({
  displayName: 'HeyHey',

  render: function() {
    console.log(this.displayName);
  }
});

How do I do the same thing inside a stateless component?

Javascript Solutions


Solution 1 - Javascript

The docs for displayName say

> The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see Wrap the Display Name for Easy Debugging for details.

In your case, you would simply use

const MyComponent = (props) => { ... }

MyComponent.displayName = 'HeyHey'

Or you can use Object.assign

const MyComponent =
  Object.assign
    ( props => { ... }
    , { displayName: 'HeyHey' }
    )

Solution 2 - Javascript

Figured it out

const MyComponent = props => {
  return (
    <p>How you doin?</p>
  )
}

MyComponent.displayName = "MyComponent"

Solution 3 - Javascript

React either needs displayName for functional components when they're defined as arrow functions, or the name of the function itself.
So for arrow functions:

const SomeComponent = () => <p>I come from an arrow function</p>

SomeComponent.displayName = 'HeyHey'

If you use a function, it'll use its name as displayName without having to define it separately:

function HeyHey() { return <p>I come from a non-arrow function!</p> }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiona53-416View Question on Stackoverflow
Solution 1 - JavascriptMulanView Answer on Stackoverflow
Solution 2 - Javascripta53-416View Answer on Stackoverflow
Solution 3 - JavascriptRazorView Answer on Stackoverflow