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 (pao) isn't picking it up. Am I setting it incorrectly? I've also tried setting it outside the class like stateless ponents MyClass.displayName = 'Test' which also doesn't have an effect.
Edit: The answer is: static displayName = 'CustomTestUI'
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 (pao) isn't picking it up. Am I setting it incorrectly? I've also tried setting it outside the class like stateless ponents MyClass.displayName = 'Test' which also doesn't have an effect.
Edit: The answer is: static displayName = 'CustomTestUI'
-
5
have you tried
static displayName = 'yourName'
? – Dayan Moreno Leon Commented Aug 23, 2017 at 4:42
2 Answers
Reset to default 4As stated in the ments, 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 ponent class in this error and this function.
You can also set the displayName
of a ponent via Component.displayName = 'myName'
.
class TestUI extends React.Component {
...
}
TestUI.displayName = 'CustomTestUI';
The ments 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'
}
}