I have some non-sensitive data that I need to set to different values based on what environment node runs in staging
or production
. I believe accessing something like process.env.NODE_ENV
will not work within a react ponent itself, only in a server-side file, hence need a way to somehow pass this down to my react ponent.
It is simply to show if string "Staging" or "Production" inside the footer ponent.
I have some non-sensitive data that I need to set to different values based on what environment node runs in staging
or production
. I believe accessing something like process.env.NODE_ENV
will not work within a react ponent itself, only in a server-side file, hence need a way to somehow pass this down to my react ponent.
It is simply to show if string "Staging" or "Production" inside the footer ponent.
Share Improve this question edited Apr 8, 2020 at 20:24 Niroshan Ratnayake 3,8013 gold badges21 silver badges19 bronze badges asked Jun 28, 2016 at 11:04 IljaIlja 46.5k103 gold badges289 silver badges527 bronze badges 1-
I think you should have the
__DEV__
variable accessible from any ponent in your application. – martinarroyo Commented Jun 28, 2016 at 11:12
2 Answers
Reset to default 8Consider 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: []
};
}
ponentDidMount() {
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/