Nisarg Thakkar
Nisarg Thakkar

Reputation: 1547

How to get environmental variables in MainApplication.java react native

I have created process.env.key file and i want this variable in MainApplication.java and strings.xml file

Can you please help me how to get variable?

Upvotes: 5

Views: 1501

Answers (1)

Brendon Hudson
Brendon Hudson

Reputation: 36

After a long time trying to do the same thing, I finally win using a react native library with native integration for environment variables: react-native-config

I recommend you to read the README.md file with the most updated installation and use steps, but, I will put here the exact steps that I did to can do it. https://github.com/luggit/react-native-config#native-usage

SOLUTION STEPS

  1. First install the react-native-config library:
yarn add react-native-config
react-native link react-native-config
  1. Add inside your MainApplication.java file this code where you need to use the environment var:
// example, here I added the code inside onCreate() method of my MainApplication class
public void onCreate() {
    String VAR_WITH_ANY_NAME = BuildConfig.ANY_ENV_VAR_AS_YOU_WANT;
   // ... any code ...
  }

(I think you had created your .env file with the needed variables)

  1. Now, rebuild your project (I like to do it in different terminals, one for the bundle and another for build)
    • Init your js bundle with yarn && yarn start --reset-cache in a terminal.
    • Recompile your native project with yarn run android in another terminal.

Upvotes: 2

Related Questions