Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - How can I access the displayName of a component using javascript?

I'm building some React components and sometimes would like to log to the console the type of component that's being rendered, by displayName, which JSX uses when displaying the name of a component.

From the context of a component, how can I access the displayName property?

e.g. how can I make the console.log statement in this example show the displayName of the component?

var Hello = React.createClass({     displayName: 'HeyHey',      render: function() {         console.log(this.displayName);          return <div>Hello {this.props.name}</div>;     } }); 

Intended output in console:

HeyHey

like image 926
Brad Parks Avatar asked Jul 12 '14 00:07

Brad Parks


People also ask

How do you find the ID of a React component?

To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .

How do you get the name of the React component?

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 access the element DOM in React?

We access a DOM element using the current property of a reference created with the React. createRef() function. React will update this property with an actual DOM element after render and before update events. That means that we can access the DOM element in componentDidMount and componentDidUpdate functions.


1 Answers

It's available as the public property this.constructor.displayName.

like image 182
Jacob Rask Avatar answered Oct 14 '22 11:10

Jacob Rask