How To Use Environment Variables In React

In this article, we will learn how to use environment variables in React.

–First of all, we have create react application.

–Then open a root directory and create a .env file inside that directory.

–Open the .env file and set your environment variable.

REACT_APP_PROJECT_NAME=my env file demo

use REACT_APP prefix in all custom variables. without REACT_APP  is ignored.

— Now open your file and use environment variables.

First, you need to put process.env before your custom variable.

process.env.REACT_APP_PROJECT_NAME

–And again start your application npm start to see the changes.

–My app.js file

import React from 'react'

export default function App() {

let myData = process.env.REACT_APP_PROJECT_NAME
  return (
    <>
      <h1>{myData}</h1>
    </>
  )
}

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories