Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.