.env file example react native
What is an .env file in React Native?
React Native is a popular framework for building cross-platform mobile applications. When building a React Native app, you may need to use sensitive information such as API keys, database credentials, and other configuration variables. The .env file is a simple solution to store this sensitive information in a safe and secure manner.
Example of .env file in React Native
API_KEY=xyz123
API_SECRET=abc456
DATABASE_URL=https://example.com/db
The .env file should be located in the root directory of your React Native project. This file is not included in version control, so it won't be shared with other developers or stored in a public repository like Github. Instead, you should add the .env file to your .gitignore file to prevent it from being committed.
How to use .env variables in React Native
To use .env variables in your React Native app, you first need to install the "react-native-dotenv" package:
npm install react-native-dotenv --save-dev
This package is a zero-dependency module that provides a simple way to load environment variables into your React Native app.
Once you've installed the package, you can import the variables from your .env file:
import { API_KEY, API_SECRET, DATABASE_URL } from 'react-native-dotenv';
You can then use these variables wherever needed in your code:
fetch(`${DATABASE_URL}/users`, {
headers: {
'Api-Key': API_KEY,
'Api-Secret': API_SECRET
}
})
Alternative ways to use .env variables in React Native
There are other ways to use .env variables in your React Native app, such as:
- Using the "dotenv" package, which provides a similar solution but with a different syntax.
- Using platform-specific files, such as ".env.android" and ".env.ios", to define environment variables that are specific to each platform.
Ultimately, the choice of how to store and use environment variables in your React Native app depends on your specific needs and preferences.