Search code examples
reactjs

Component definition is missing display name for forwardRef


I was following this tutorial on using React.forwardRef, where make this component:

import React from "react";

const Search = React.forwardRef<HTMLInputElement>((props, ref) => {
  return <input ref={ref} type="search" />;
});

export default Search;

However, running my app, the component causes the following error:

Component definition is missing display name  react/display-name

Based on this question, I thought I might do something like this:

const Search = MySearch = React.forwardRef<HTMLInputElement>((props, ref) => {
  return <input ref={ref} type="search" />;
});

export default Search;

But this did not fix the problem either.

So then, how can I give my component a display name?


Solution

  • The Component definition is missing display name react/display-name message is likely coming from a tool like eslint.

    It is a linting rule that exists in order to help you follow style guides and/or conventions regarding what is considered good practice when writing React code.

    That particular rule in eslint is explained in further details here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md

    From that page you can also find why it exists and what the displayName property on React Components is good for, namely to help when debugging, since it means that it will print your component's displayName property to the console instead of just input.

    Also, from that link, you can find that when you are using function components, you can address that by setting the displayName property on the component. This should probably help you:

    import React from "react";
    
    const Search = React.forwardRef<HTMLInputElement>((props, ref) => {
      return <input ref={ref} type="search" />;
    });
    Search.displayName = "Search";
    
    export default Search;
    

    Another option is to just disable that particular linter, using a comment with // eslint-disable-next-line react/display-name or similar just above the declaration of your component.

    That would however mean that if you were to need to debug your app, this component would simply be called input instead of Search, which might make the debugging a bit harder.