Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export variable from class React

In my app.js inside the app class there is a variable that I want to export to another module. I tried many options, but unfortunately, the understanding of how to do it correctly did not come. Tell me, please, how to do it right? Export default is already in use in my class

export class App extends Component {
    static propTypes = {
        //somecode
    };

    constructor(...args: any): void {
        super(...args);
    }

    render() {
        // console.log('app render start');
        const test = true;
        return (
        //somecode
        );
    }

    componentDidMount() {
        //somecode
    }


    componentDidUpdate(prevProps): void {
        //somecode
    }
}

In the example above, i need to export variable 'test'

I would be grateful for any help.

like image 589
A.Burdonskaya Avatar asked Feb 05 '19 04:02

A.Burdonskaya


People also ask

Can I export a variable in React?

If you are exporting a variable (or an arrow function) as a default export, you have to declare it on 1 line and export it on the next. You can't declare and default export a variable on the same line.

Can you export a class in React?

In React we use the keyword export to export a particular module or a named parameter or a combination. Let us now see the different ways we can use the import operation in React. Exporting default export: We have already learned that every module is said to have at most one default export.


1 Answers

Assuming your intention with test is to define something like a "project constant" (which is what I gather, from your use of the const keyword), then you could simply declare test outside of the App class, and then export it from the module in the same way you are exporting the class:

App.js
/*
Export test variable
*/
export const test = true;

/*
Export your App class
*/
export class App extends Component {
    static propTypes = {
        //somecode
    };

    constructor(...args: any): void {
        super(...args);
    }

    render() {
        /*
        Access test variable in "global scope" inside render method
        */
        console.log(`test is: ${ test }`);

        // console.log('app render start');
        // const test = true;
        return (
        //somecode
        );
    }

    componentDidMount() {
        //somecode
    }


    componentDidUpdate(prevProps): void {
        //somecode
    }
}

And then, from another module in your project you could access test like so:

MyModule.js
import { App, test, } from 'path/to/App';

console.log(`test is: ${ test }`);
like image 154
Dacre Denny Avatar answered Sep 27 '22 20:09

Dacre Denny