Friday, June 10, 2022
HomeWeb DevelopmentUnderstanding React Native env variables

Understanding React Native env variables


Variables are one of many elementary elements of programming languages. In JavaScript, a variable shops the worth of knowledge varieties akin to integers, strings, and extra. The worth or knowledge kind of a variable may be modified later.

On this article, we’ll find out about setting variables, why they’re helpful, and find out how to use them in React Native. We’ll cowl:

What’s an env variable?

Variables can play totally different roles in React Native. For instance, you possibly can use CSS variables in React Native to retailer and implement customized types.

An setting variable — or as it’s popularly identified, an env variable — is a variable whose worth is about from outdoors this system. It’s used to retailer info like API endpoints, listing paths, and so forth.

If you wish to cut back repetition in your code, utilizing an env variable helps you DRY code. All you must do is write or outline your variable in your root folder. Then, you possibly can import the variable in your element earlier than calling it.

Whereas env variables are very helpful in React Native, it isn’t advisable to make use of them to retailer delicate info like API keys, authentication keys, or passwords. They don’t seem to be safe for varied causes.

For instance, env variables don’t encrypt their values. They’re additionally embedded into the applying’s construct, which implies that anybody can view them by inspecting your app’s information.

How one can create a customized env variable in React Native

Let’s check out an instance of making env variables in React Native.

Your first step is to go to your root folder and create a .env file. Inside this file, write the API endpoint with none parentheses, as seen beneath:

REACT_APP_BASE_URL=https://api-dev.utility.com

Then, inside your element, name the env variable as proven within the instance beneath:

import React, { useState, useEffect } from "react";
import { View, Textual content } from "react-native";

const App = () => {
  const postUrl = course of.env.REACT_APP_BASE_URL
  return (
    <View
      type={{
        flex: 1,
        justifyContent: "heart",
        alignItems: "heart"
      }}
    >
      <Textual content>ENV URL: {postUrl} </Textual content> // https://api-dev.endpoint.com
    </View>
  );
};
export default App;

Discover how we outlined the env variables in course of.env. within the instance above. This step permits us to make use of course of.env. to entry the env variables.

It’s pertinent to notice that every one our customized env variables in React Native should start with REACT_APP_. Any variables with out the REACT_APP_ prefix will probably be ignored, and we won’t be able to entry them in our utility.

What’s NODE_ENV?

NODE_ENV is a built-in env variable that’s used to state whether or not a specific setting is a growth, testing, or manufacturing setting. Not like our customized env variables in React Native, NODE_ENV doesn’t want the REACT_APP_ prefix.

To make use of NODE_ENV to verify which setting you might be at present engaged on, you are able to do the next in your App.js file:

const setting = course of.env.NODE_ENV
console.log(setting)

In the event you’re working in a growth setting (i.e., once you run npm begin), console.log(setting) will print growth.

In the event you’re working in a testing setting (i.e., once you run npm take a look at), console.log(setting) will print take a look at.

In the event you’re working in a manufacturing setting (i.e., once you run npm construct to push to manufacturing), console.log(setting) will print manufacturing.

NODE_ENV can’t be overridden manually, which will help hold builders from deploying a gradual growth construct to manufacturing accidentally.

Utilizing env variables to modify between API endpoints in several environments

You should use env variables to render info conditionally primarily based on the setting. For instance, we are able to swap between API endpoints in growth, testing, and manufacturing utilizing NODE_ENV.

Chances are you’ll be questioning why environment-based rendering for API endpoints and different info is even obligatory. One necessary motive is in order that we are able to make modifications or scorching fixes in manufacturing or add new options in growth with out breaking the manufacturing construct.

Let’s say we have already got a reside model of our utility, however we wish to add a brand new function or make another change. We don’t wish to make this modification within the manufacturing setting as a result of we would break the applying.

As a substitute, we must swap to the event setting, make the mandatory modifications, and take a look at. We may additionally swap to the staging setting to ensure every thing is okay and nothing breaks earlier than we push to manufacturing.

We will probably be constructing out a quite simple React Native utility to assist exhibit how we are able to use env variables to modify between API endpoints in several environments. To comply with together with the remainder of this text, it is best to know find out how to work with React Native.

Putting in and configuring the dotenv bundle

There are many React Native element libraries and packages that assist present a easy dev expertise. Some packages will help us simply entry our env variables in React Native, together with dotenv, react-native-config, and so forth.

For the needs of this text, we will probably be utilizing the dotenv bundle. The dotenv bundle permits you inject your env variable right into a React Native setting.

To put in dotenv with NPM, run the command beneath:

$ npm set up react-native-dotenv

To put in dotenv with yarn, run the command beneath:

$ yarn add react-native-dotenv

After putting in the bundle, spin up your utility. Then, let’s configure the plugins.

To configure the put in bundle, go to your .babelrc or babel.config.js file positioned in your root folder and add the next:

module.exports = {
  plugins: [
    [
      "module:react-native-dotenv",
      {
        envName: "APP_ENV",
        moduleName: "@env",
        path: ".env"
      }
    ]
  ]
};

Right here, we configured our dotenv bundle. We additionally assigned a path to the .env file, the place our env variables will probably be saved. Lastly, we assigned a module named @env, from which we are able to import our env variables.

Defining our customized env variables in our .env file

Subsequent, let’s create our .env file in our root folder. The .env file is a textual content file we’ll use to outline our variables, as proven beneath.

REACT_APP_DEV_MODE=https://api-dev.utility.com
REACT_APP_PROD_MODE=https://api-prod.utility.com
REACT_APP_STAGE_MODE=https://api-stage.utility.com
REACT_APP_TEST_MODE=https://api-test.utility.com

As you possibly can see above, we outlined our customized env variables utilizing the REACT_APP_ prefix.

Importing and calling variables from our @env module

Subsequent, let’s go over to our App.js file and import the variables from the @env module, which we configured earlier in our babel.config.js file.

import React from "react";
import { REACT_APP_DEV_MODE, REACT_APP_PROD_MODE } from "@env"

After now we have imported our variables, we are able to name them and fetch our API endpoints with them.

import React from 'react';
import { View, Textual content, StyleSheet } from 'react-native';
import { REACT_APP_DEV_MODE } from '@env';

const App = () => {
    return (
        <View type={types.display screen}>
            <Textual content>Url: {REACT_APP_DEV_MODE}</Textual content> // https://api-dev.utility.com
        </View>
    );
};

const types = StyleSheet.create({
    display screen: {
        flex: 1,
        justifyContent: 'heart',
        alignItems: 'heart'
    }
});
export default App;

We now have seen find out how to configure our dotenv bundle, create our env variables, and name env variables from our @env module. Lastly, allow us to use this information to modify between API endpoints in several environments.

Checking the setting and dynamically calling the env variable

Earlier, we discovered that we are able to use NODE_ENV to verify which React Native setting we’re in. We are able to then swap between API endpoints conditionally primarily based on that setting.

The beneath code exhibits two methods to attain this. The primary method is by importing the env variables we outlined in our .env file. The second method is by utilizing course of.env.

// utilizing the @env bundle
import { REACT_APP_DEV_MODE, REACT_APP_PROD_MODE } from '@env';

const url =
        course of.env.NODE_ENV === 'growth'
            ? REACT_APP_DEV_MODE
            : REACT_APP_PROD_MODE;

// Or utilizing course of.env
const url =
        course of.env.NODE_ENV === 'growth' ? course of.env.REACT_APP_DEV_MODE : course of.env.REACT_APP_PROD_MODE;

In every methodology, we first checked the setting, then dynamically referred to as the corresponding env variable.

Conclusion

On this article, we noticed why utilizing env variables in React Native is necessary. We additionally discovered find out how to create customized env variables and use them to dynamically swap between API endpoints in several environments.

I hope this text has helped you perceive React Native env variables higher. Thanks for studying!

LogRocket: Immediately recreate points in your React Native apps.

LogRocket is a React Native monitoring answer that helps you reproduce points immediately, prioritize bugs, and perceive efficiency in your React Native apps.

LogRocket additionally helps you enhance conversion charges and product utilization by displaying you precisely how customers are interacting along with your app. LogRocket’s product analytics options floor the the reason why customers do not full a specific movement or do not undertake a brand new function.

Begin proactively monitoring your React Native apps — .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments