Home > Enterprise >  React - Get displayName of functional component inside the component?
React - Get displayName of functional component inside the component?

Time:04-11

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";

CodePudding user response:

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.

CodePudding user response:

Also, with displayName:

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

  handleOnPress();
};

MemoizedCarWasher.displayName = "CarWasher";

MemoizedCarWasher();

  • Related