How set displayName to a React stateless component with memo?

Viewed 489

This is a exemple the implementation of the stateless component:

import React, { memo } from 'react';

const Create = memo(props => {
    return <div id={props.id}>CREATE TEST</div>;
});

Create.displayName = "Create";

export default Create;

In React Developer Tools on Chrome is displayed like a Anonymous component (highlighted line):

enter image description here

2 Answers

You can use Object.assign:

const Create = memo(
  Object.assign(props => {
    return <div id={props.id}>CREATE TEST</div>;
  }, { displayName: 'Create' } )
)

You can also look at this issue, you may use any workaround solutions if above solution isn't helpful for you.

As for every component in React, React DevTools look for either the name or displayName property of the component itself.

You can, therefore, simply set the displayName property:

export const SomeButton = memo(() => { ... });
SomeButton.displayName = 'SomeButton';

But memo() itself retrieves the name from the passed component, so you can also use a named function expression instead of an arrow function:

export const SomeButton = memo(function SomeButton() { ... });
Related