DEV Community

Dallington Asingwire
Dallington Asingwire

Posted on • Updated on

 

How to use .env file in a React Native Application

Using environment file (.env) to configure most critical variables like database credentials, api keys, is the most common practice in software development. In this post, we are going to see how to create and use .env file in react native.

First, we need to install and use a babel plugin called react-native-dotenv. Install this plugin under your project root directory using the command below;

npm install react-native-dotenv
Enter fullscreen mode Exit fullscreen mode

This babel plugin lets you inject your environment variables into your react-native application.

.env file
Create .env file under your project root directory and example looks like below;

APP_NAME=MyRNApp
COMPANY_EMAIL=yyy@xxxx.com
API_KEY=myapikeyisplacehere
Enter fullscreen mode Exit fullscreen mode

Create if you don't have babel.config.js file under your project root directory, and add the following code

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    ["module:react-native-dotenv", {
      "envName": "APP_ENV",
      "moduleName": "@env",
      "path": ".env",
      "safe": false,
      "allowUndefined": true,
      "verbose": false
    }]
  ]
};

Enter fullscreen mode Exit fullscreen mode

How to access and use environment variables in your components

import React from 'react'
import {View, Text} from 'react-native'
import {APP_NAME, API_KEY, COMPANY_EMAIL} from '@env'

const App = () => {
return (
   <View>
    <Text>My App name is {APP_NAME}</Text>
    <Text>My API Key is {API_KEY}</Text>
    <Text>Company email is {COMPANY_EMAIL}</Text>
   </View>
);
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Output on your emulator or phone device screen

My App name is MyRNApp
My API Key is myapikeyisplacehere
Company email is yyy@xxxx.com
Enter fullscreen mode Exit fullscreen mode

As you can see the above output, we have been able to load environment variables,APP_NAME, API_KEY and COMPANY_EMAIL into our react native application.

And that's the basic example of how you can use a .env file in a react native application. Thank you for reading through this article.

Top comments (6)

Collapse
 
codingalgorithm profile image
Taofeek Ibrahim Opeyemi

Thank you.. This was helpful.

Collapse
 
k3nnet profile image
k3nnet

Danko . this was helpful.

Collapse
 
wilmela profile image
Wilmela

Thank you. This was helpful.

Collapse
 
dallington256 profile image
Dallington Asingwire

@wilmela , Glad to hear that!

Collapse
 
mkhuzo profile image
mkhuzo zulu

worked perfectly

Collapse
 
marcoottina profile image
MarcoOttina

What to do if the '@env' is not found despite following each steps?