To utilize environment variables in index.html while creating a React app, you can follow these steps:
.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.
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>
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.
Asked: 2022-09-12 11:00:00 +0000
Seen: 8 times
Last updated: Oct 31 '21