How can we set up .env in react native application?

Viewed 16042

How can we set up .env in react native application? How to do environment setup inside react-native.

3 Answers

I use 'react-native-dotenv' package. Install it and add "react-native-dotenv" preset to your .babelrc file at the project root, like this:

{
  "presets": ["react-native", "react-native-dotenv"]
}

Then create a .env file and add your properties there, may be like this:

YOUR_FIELD="value"

finally, you should be able to use it in your src files, like this:

import { YOUR_FIELD } from 'react-native-dotenv';
console.log(YOUR_FIELD) // prints "value"

if you run into an issue while using this package, then you can look for further clarification in their GitHub page, right here: https://github.com/zetachang/react-native-dotenv

Hope this helps.

In React Native CLI First install https://www.npmjs.com/package/react-native-dotenv this package Then Create .env file in your Route Folder of your project and set urls like this

REACT_APP_API_BASE_URL='https://api/v1'
REACT_APP_BT_AUTHORIZATION='....vynf6nzv'

After this, Create Config.js file in Route Folder and import your URLS like this

import {REACT_APP_BASE_URL, REACT_APP_API_BASE_URL} from '@env';

export default {
  REACT_APP_BASE_URL,
  REACT_APP_API_BASE_URL,
};

To Use these URLS You can simply import config file in any file you want and use it like this one //Importing config file

import config from '../../../config';

//Using config file to set urls

**`${config.REACT_APP_API_BASE_URL}/user_requests`**

Thanks.

Two options

1) If you are using a project with native code, you can use react-native-config. This gives you the added benefit of using your .env variables in your android and iOS project files.

2) If you are using expo, react-native-dotenv is the way to go.

Related