react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

Functional component name

Open ricardo-reis-1970 opened this issue 2 years ago • 0 comments
trafficstars

I'm using:

  • "react": "^18.2.0",
  • "vite": "^4.1.0",

I need to know a component's name inside the component, or inside the module where the component is defined. The reason I need this is for debug purposes. I want to prefix my log messages with the component's name and I think that putting this manually is clumsy and non-portable.

I saw a lot of answers on SO that simply put do absolutely nothing, many of them referring to class components (because people can't read). One of these, however, refers to React's own documentation here. Granted, this comes under Class Properties, but the text clearly states that "The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. ". Am I misreading this?

After hours trying to fix this, the unsuccessful attempts include:

  • setting the name property: failed, because it's read only; also, its value is "".
  • setting the displayName property: it's non-portable;
  • trying the log function both inside and outside the component's function:
const log = (...a) => console.log(`[${<SOMETHING_THAT_WORKS_PLEASE>}]`, ...a)

As I said, the only thing that I could make work so far is replacing <SOMETHING_THAT_WORKS_PLEASE> with 'componentName'`, which again is really non-portable.

Is there any way to get this name?

ricardo-reis-1970 avatar Mar 13 '23 09:03 ricardo-reis-1970