Get component name in React

reactjs

Solution

You don't need it to be dynamic since you are writing the component yourself and can pass it as a string

class LoginForm extends React.Component {
    render() {   
        return (
            <div className="login-form-root">
                 {this.state.displayLoading && <Loading loadingFrom="LoginForm "/>}
            </div>
        );
    }
}

However if you still need to access the name of the component, you could define the `displayName` property on the component

class LoginForm extends React.Component {
   static displayName = 'LoginForm';
    render() {   
        return (
            <div className="login-form-root">
                 {this.state.displayLoading && <Loading loadingFrom="LoginForm "/>}
            </div>
        );
    }
}

and access it like `Component.displayName`.

Problem

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.

Original source

Related problems