I'm developing a React application. I have a Loading component, which is a little animation for waiting. I want to add a message in this Loading component according to the component which called it.
Here is how i call my Loading component (with this.state.displayLoading at true or false) :
class LoginForm extends React.Component {
render() {
return (
<div className="login-form-root">
{this.state.displayLoading && <Loading loadingFrom={?}/>}
</div>
);
}
}
I want to get "LoginForm" in my variable loadingFrom, which is the className. Maybe it's not the right way to do that.
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.
displayName. The displayName string is used in debugging messages. Usually, you don't need to set it explicitly because it's inferred from the name of the function or class that defines the component.
What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates.
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function 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.
https://reactjs.org/docs/react-component.html#displayname
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'
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