DEV Community

DALLINGTON ASINGWIRE
DALLINGTON ASINGWIRE

Posted on

Using .env file in a React Native Application

Using environment file to configure most critical variables like api keys, is the most common practice done in most react, react native, Laravel applications etc. In this post, we are going to see how to create and use .env file in react native.

Firstly, we install and use the dependency package react-native-dotenv. Install this package using the command below under your project root directory npm i react-native-dotenv or yarn add react-native-dotenv

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

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 paste the following code

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

Enter fullscreen mode Exit fullscreen mode

Using environment variables in your components

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

const App = () => {
return (
   <View>
    <Text>{API_KEY}</Text>
   </View>
);
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Output on your device screen

myapikeyisplacehere
Enter fullscreen mode Exit fullscreen mode

That's how you can use a .env file in a react native application. Thank you for reading through this short article.

Discussion (0)