Ask Your Question
2

How to utilize environment variables in index.html while creating a React app?

asked 2022-09-12 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-31 08:00:00 +0000

nofretete gravatar image

To utilize environment variables in index.html while creating a React app, you can follow these steps:

  1. Create a .env file at the root of your project directory and define the environment variable inside it. For example:
REACT_APP_TITLE="My Awesome App"

Note: the prefix REACT_APP_ is necessary for React to recognize the environment variable.

  1. In your index.html file, you can use the ${process.env.REACT_APP_VARIABLE_NAME} syntax to access the environment variable value. For example:
<!DOCTYPE html>
<html>
  <head>
    <title>${process.env.REACT_APP_TITLE}</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
  1. In your JavaScript code, you can access the environment variable in the same way as above, using the process.env.REACT_APP_VARIABLE_NAME syntax. For example:
import React from 'react';

function App() {
  return (
    <div>
      <h1>{process.env.REACT_APP_TITLE}</h1>
    </div>
  );
}

export default App;

Note: remember to restart the development server after adding or modifying environment variables, for them to take effect.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-12 11:00:00 +0000

Seen: 8 times

Last updated: Oct 31 '21