reactjs / reactjs/react.dev

Functional component name

Open
#5,673 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the React Component documentation linked in the issue and reproduce the question using React 18.2.0 with Vite 4.1.0, checking both inside and outside a functional component. Done means the documentation clearly explains whether the component name is available in this context and what supported debugging guidance applies.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react, vite
Domain
documentation, frontend
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.