accessing environment variable from react component
Consider using the DefinePlugin:
Define free variables. Useful for having development builds with debug logging or adding global constants.
Example:
new webpack.DefinePlugin({ VERSION: JSON.stringify("5fa3b9"), BROWSER_SUPPORTS_HTML5: true, TWO: "1+1", "typeof window": JSON.stringify("object") })
create-react-app creates a React app with environment variable access.
So you could use process.env.NODE_ENV
in your code without any additional steps.
It also makes any environment variable starting with REACT_APP_
available to the app.
You get .env support as well.
Example
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
users: []
};
}
componentDidMount() {
fetch(process.env.REACT_APP_SERVER_URL)
.then(response => response.json())
.then(users => this.setState({ users }));
}
render() {
return (
<div className="App">
<header className="App-header">
<h1>Env var demo</h1>
</header>
<main>
<ul>
{this.state.users.map(user => (<li key={user.id}>Name: {user.name}</li>))}
</ul>
</main>
<footer className="App-footer">
<p>ENVIRONMENT: {process.env.NODE_ENV}</p>
</footer>
</div>
);
}
}
export default App;
Refer to the environment variables documentation: https://create-react-app.dev/docs/adding-custom-environment-variables/