'how to get current react component name inside custom react hook?
I have a custom hook
function myCustomHook() {
const currentComponentName = //?
return `currentComponentName${customSuffix}`
}
function Sample() {
const name = myCustomHook()
}
function Component2() {
const name = myCustomHook()
}
is it possible to get the unique name of a component? or any other alternative for this use case?
Solution 1:[1]
const getName = () => {
const stack = new Error().stack;
const lines = stack.split("\n");
const line = lines[3];
const match = line.match(/at (.*) \(/);
const name = match[1];
return name;
};
I got it using copilot...
Solution 2:[2]
Maybe useRef can help to deal with your case https://medium.com/trabe/react-useref-hook-b6c9d39e2022
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 | Ray Silva |
| Solution 2 | Dmytro Ilhanaiev |
