'React - Get displayName of functional component inside the component?

Is it possible to get the name of a functional component inside it?

Something like:

function CarWasher(props) {
  const handleOnPress = () => {
    console.log(this.displayName); // <-- Something like this displayName
  }

  return ...JSX;
};

CarWasher.displayName = "CarWasher";


Solution 1:[1]

You can reference the .name property of the function.

function CarWasher(props) {
  const handleOnPress = () => {
    console.log(CarWasher.name);
  }
  handleOnPress();
};

CarWasher();

If you're worried about accidentally making a typo when referencing one of the above variables, consider using TypeScript or at least the no-undef ESLint rule.

Solution 2:[2]

Also, with displayName:

function MemoizedCarWasher(props) {
  const handleOnPress = () => {
    console.log(MemoizedCarWasher.displayName);
  }

  handleOnPress();
};

MemoizedCarWasher.displayName = "CarWasher";

MemoizedCarWasher();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance
Solution 2 Victorio Molina