How to define and use environment variables in React app

How to define and use environment variables in React app

In this post we will give you information about How to define and use environment variables in React app. Hear we will give you detail about How to define and use environment variables in React appAnd how to use it also give you demo for it if it is necessary.

Environment variables help us to use different configurations in our react app for example we can use different API for development and different for production without changing the whole app every time or hiding the feature which is not ready for production yet.

Defining Environment Variables

To define environment variables, first we need to create a file .env file in the root folder of our react app.

Now, we can define environment variables inside that file using REACT_APP_.VARIABLE_NAME=VALUE.

.env
REACT_APP_.BASE_URL=https://google.com

Note: Don’t commit .env file to your public GitHub repository, if you stored secrets like API_KEY or passwords.

Accessing Environment Variables

In our react app components, we can access the environment variables by using process.env.REACT_APP_.BASE_URL.

App.js
import React from "react";export default function App(){   return (      <div>        <a href={process.REACT_APP_.BASE_URL}>My app</a>      </div>   )}

Inside the public/index.html file we can access environment variables like this.

index.html
<base href="%REACT_APP_BASE_URL%">

The environment variables are injected into the app at build time.

Hope this code and post will helped you for implement How to define and use environment variables in React app. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US