Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set displayName in a functional component [React]

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?

like image 618
a53-416 Avatar asked Apr 11 '17 20:04

a53-416


People also ask

Can we use refs in functional component?

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . You may not use the ref attribute on function components because they don't have instances.

How do you get a component name?

To get a component's name in React, we can use the displayName property. to set the Foo. displayName property to the name we want. Then we can retrieve it in the code and the React developer tools.

What is a React memo?

React. memo is a higher order component. If your component renders the same result given the same props, you can wrap it in a call to React. memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.


2 Answers

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' }     ) 
like image 162
Mulan Avatar answered Sep 28 '22 08:09

Mulan


Figured it out

const MyComponent = props => {    return (      <p>How you doin?</p>    )  }    MyComponent.displayName = "MyComponent"
like image 45
a53-416 Avatar answered Sep 28 '22 10:09

a53-416