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?
To get a component's name in React, we can use the displayName property. to set the Foo. displayName property to the name we want. Then we can retrieve it in the code and the React developer tools.
In React hooks, due to the way state is encapsulated in the functions of React. useState() , if a callback gets the state through React. useState() , it will be stale (the value when the callback was setup). But if it sets the state, it will have access to the latest state through the passed argument.
You assigned the component in a variable. var TestComponent = React. createClass({ render: function() { return <h1>Hello, {this.props.name}</h1>; } }); Now displayName is set to TestComponent .
As seen in the code examples, using hooks to encapsulate shared logic is a good start, but we can keep exploring more. Inspired by the concept of “partial application”, we can try to return a component with props that have been partially bound from a custom hook.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With