I've tried several methods in setting the display name for my React Component, but none has worked: I tried to set it as a public static variable like this:
class Base extends React.Component<any, any>{
public static displayName = "Base";
constructor(props){
...
}
render(){
...
}
}
But eslint still throws me this error:
error Component definition is missing display name react/display-name
I tried an alternative approach where I set it outside the class definition:
class Base extends React.Component<any, any>{
constructor(props){
...
}
render(){
...
}
}
Base.displayName = "Base";
And I end up getting an error saying:
Property 'displayName' does not exist on type 'typeof Base'.
I've tried different methods from other Stackoverflow posts but I can't seem to get rid of the error. How can I resolve this? Please help.
edit: answered my own question below. The core of this problem seemed to be regarding anonymous functions rather than the React class.
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'
Classes are set using the className attribute ( class is a reserved word in React). Inline styles can be set using the styles attribute. Conditionally setting the className attribute can be useful in many ways. For instance, you could implement a switch element that allows users to toggle between the dark and light modes.
ES6 introduced classes. A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor () method. Notice the case of the class name. We have begun the name, "Car", with an uppercase character. This is a standard naming convention for classes.
React is a popular JavaScript-based framework for developing website UI. It uses the template language JSX, like HTML but has dynamic features. One of the biggest advantages of JSX is that it allows you to apply attributes conditionally. Classes are set using the className attribute ( class is a reserved word in React).
Instead of using public static displayName = "Base";
remove public and use it like static displayName = "Base";
class Base extends React.Component<any, any>{
static displayName = "Base";
constructor(props){
...
}
render(){
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With