The best way to handle environment variables in React Native is to use the react-native-config
library.
Here are the steps:
- Install the library
npm install react-native-config
Or if you use Yarn:
yarn add react-native-config
- Create .env file
Then you can create a .env
file on the root of your project and add your environment variables like this:
API_URL=https://myapi.com
If you have different environments (like production, staging, development), you can create different .env
files like .env.production
, .env.staging
etc.
- Link the library
For Android, open android/app/build.gradle
and add the following at the top
apply from: project(":react-native-config").projectDir.getPath() + "/dotenv.gradle"
For iOS, open the ios project folder in xcode and open Pods>Podfile and add react-native-config dependency in IOS
pod 'react-native-config/Extension', :path => '../node_modules/react-native-config'