Certainly! Let’s delve into more details for both React.js and React Native.
React.js (Web)
1. Install dotenv package:
If you’re not using Create React App or a similar tool that automatically handles environment variables, you might need to install the dotenv
package:
npm install dotenv
2. Configure your application:
In your main application file (e.g., index.js
or App.js
), import and configure dotenv at the top:
// index.js or App.js
import dotenv from 'dotenv';
dotenv.config();
// ... rest of your code
3. Access the variable in your code:
After configuring dotenv, you can access the environment variable in your components:
const apiUrl = process.env.REACT_APP_API_URL;
Make sure that the environment variable is prefixed with REACT_APP_
, as this is a convention in Create React App.
React Native
1. Configure Metro bundler:
If you’re not using react-native-dotenv
and prefer to use Metro’s default behavior, you can add the following to your metro.config.js
:
module.exports = {
resolver: {
sourceExts: ['jsx', 'js', 'tsx', 'ts'], // Add any other extensions you need
},
};
2. Access the variable in your code:
In your React Native components, you can import and use the environment variable like this:
import { API_URL } from '@env';
// Use API_URL in your code
3. Build for different environments:
If you have different API URLs for development, staging, and production, you can create separate .env
files (e.g., .env.development
, .env.staging
, .env.production
) and set the appropriate file during the build process.
For example, to build for development:
react-scripts build --env=development
This would automatically pick up the .env.development
file.
4. Secure sensitive information:
Never include sensitive information such as API keys directly in your code or in version control. Use environment variables to manage such information and keep the .env
file secure.
5. Deployment:
When deploying your application, ensure that you set the environment variables in your hosting environment (e.g., Netlify, Vercel, AWS, etc.) or use the platform-specific methods for handling environment variables.
These steps should help you effectively use environment variables in both React.js and React Native applications.