How to use environment variables in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To use environment variables in react js, you have to create .env file after that you can use using process .env veriables name that,s how you can use environment variables in react js.

Today, I am going to show you, how to use environment variables in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React from 'react';

Step 3: Create a Component.

You can use <p>API URL: {process.env.REACT_APP_API_URL}</p> to use environment variables in react js.

<div>
  <h1>React Environment Variables</h1>
  <p>API URL: {process.env.REACT_APP_API_URL}</p>
  <p>Feature Enabled: {process.env.REACT_APP_FEATURE_FLAG === 'true' ? 'Yes' : 'No'}</p>
</div> 

Use environment variables example.

The below code is an example of a React. You have to import react and use console.log('API URL:', process.env.REACT_APP_API_URL) to use environment variables in react js.

Check the Location of the .env File

The .env file must be placed in the root directory of your project.

Project Structure

MY-REACT/
  β”œβ”€β”€ src/
  β”œβ”€β”€ public/
  β”œβ”€β”€ .env
  β”œβ”€β”€ package.json

App.js

import React from 'react';

const App = () => {
  console.log('API URL:', process.env.REACT_APP_API_URL);
  console.log('Feature Flag:', process.env.REACT_APP_FEATURE_FLAG);

  return (
    <div>
      <h1>React Environment Variables</h1>
      <p>API URL: {process.env.REACT_APP_API_URL}</p>
      <p>Feature Enabled: {process.env.REACT_APP_FEATURE_FLAG === 'true' ? 'Yes' : 'No'}</p>
    </div>
  );
};

export default App;

.env

REACT_APP_API_URL=https://api.example.com
REACT_APP_API_KEY=your_api_key_here

In the above code example, I have used the .env file to use environment variables in react js.

Check the output of the above code.

React, use, environment, variables

All the best πŸ‘