Get component name in React
Solution 1:
Class Components
You can use this.constructor.name
to obtain the name of your component.
(Using React 16.x as of this writing)
Caveat: This won't work if you're minifying for production with Webpack.
Functional Components
https://reactjs.org/docs/react-component.html#displayname
Solution 2:
Every React.Component
has a property called displayName
that JSX sets automatically, so theoretically you can use that property
class LoginForm extends React.Component {
render() {
return (
<div className="login-form-root">
{this.state.displayLoading && <Loading loadingFrom={this.displayName}/>}
</div>
);
}
}
UPDATE (after multiple comments saying its not working)
As per convention, react offers a code snippet to wrap getting the component name on their documentation which is the following:
function withSubscription(WrappedComponent) {
class WithSubscription extends React.Component {/* ... */}
WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
return WithSubscription;
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
As can be seen, they first check the display name, then the component name, and if all fails, then it will be just 'Component'