简体   繁体   中英

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.

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(){
        ...
    }
}

You are using this ESLint plugin I take it?

In that case, did you set ignoreTranspilerName option to true ? If so, that could be your issue.

Why even have this rule if you already have names for your component? The transpiler should use the class name as the component name by default

Answering my own question here. It turned out that the problem lies in a different area than I had originally thought. The eslint error Component definition is missing display name react/display-name was indicated where I used an anonymous function to return the React Component:

export function renderForm(){
    return {
        react: () => <Base />
    }
}

I thought that it was saying that <Base/> needed a displayName, but it turned out that the problem is the unnamed function. I resolved it by naming that function:

export function renderForm(){
    return {
        react: function renderComponent(){ return <Base />}
    }
}

Not sure if this will help anyone else, but the eslint error is now gone!

edit: changing the rule, as mentioned from the other two answers is also a valid solution fyi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM