Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set display name for a React class (ES6)?

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.

like image 732
avhhh Avatar asked Apr 20 '20 16:04

avhhh


People also ask

How to get the displayname of an arrow function in React React?

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'

How do I set a class name in react?

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.

What is a class in ES6?

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.

What is react class in react?

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).


1 Answers

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(){
        ...
    }
}
like image 54
Jagrati Avatar answered Sep 29 '22 04:09

Jagrati