Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 978
invariant Avatar asked Apr 02 '20 23:04

invariant


People also ask

How do I check my React component name?

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.

How do you get current state in React hook?

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.

How do you give a component name in React?

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 .

Can hooks return components?

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.


1 Answers

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...

like image 59
Ray Silva Avatar answered Sep 18 '22 21:09

Ray Silva