Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set displayName in class based component?

I'm trying to set the displayName property of this class that extends React.Component. The React docs say that displayName is a property, so it possible to set it in the constructor? Here's what I'm trying:

class TestUI extends React.Component {
   constructor(){
     this.displayName = 'CustomTestUI'
   }
}

But the library I'm using (pacomo) isn't picking it up. Am I setting it incorrectly? I've also tried setting it outside the class like stateless components MyClass.displayName = 'Test' which also doesn't have an effect.

Edit: The answer is: static displayName = 'CustomTestUI'

like image 674
a53-416 Avatar asked Aug 23 '17 03:08

a53-416


2 Answers

As stated in the comments, displayName should be set on the class as a static variable and not an instance using this.

class TestUI extends React.Component {
   static displayName = 'CustomTestUI';
   ...
}

Here are a couple of examples of where React retrieves displayName from the component class in this error and this function.

You can also set the displayName of a component via Component.displayName = 'myName'.

class TestUI extends React.Component {
    ...
}

TestUI.displayName = 'CustomTestUI';
like image 69
Ninjakannon Avatar answered Sep 18 '22 00:09

Ninjakannon


The comments and answers given should suffice, however I thought it a good opportunity to describe why your initial attempt did not work (and why it would have been a bad idea anyways).

When working with classes, you have the class "constructor" which is used to create many class "instances". Inside your class methods, all references to this refer to the class instance. You can always access the constructor by doing this.constructor.

So the following would have worked, though it is very bad practice for an instance to change a property on its constructor - DO NOT DO THIS:

class TestUI extends React.Component {
   constructor(){
     // DO NOT DO THIS (for educational purposes only - see other answers)
     this.constructor.displayName = 'CustomTestUI'
   }
}
like image 37
Ryan Wheale Avatar answered Sep 21 '22 00:09

Ryan Wheale