Home > other >  Get name of component from ReactElement.type.name
Get name of component from ReactElement.type.name

Time:12-09

I'm using React with Typescript and it is necessary to get the name of functional component which I found can be accessed inside of 'type' property of component component.type.name. I gave the component a type of ReactElement, because I see on console, that

$$typeof: Symbol(react.element)

But I'm getting an error from Typescript:

Property 'name' does not exist on type 'string | JSXElementConstructor'. Property 'name' does not exist on type 'string'.

That's because of the interface of ReactElement:

interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
    type: T;
    props: P;
    key: Key | null;
}

Is there any way to change the type of type to function, because I see it as a function from my console?

type: (props) => {…}

And as far as any function has a name property, to access this name property?

CodePudding user response:

I recommend using property displayName to find out a component's name: https://reactjs.org/docs/react-component.html#displayname.

CodePudding user response:

I found the answer here: Accessing child.type.name in React Typescript

This question is a duplicate for it

  • Related