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
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 .
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.
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.
It's available as the public property this.constructor.displayName
.
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