9

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 component itself, only in a server-side file, hence need a way to somehow pass this down to my react component.

It is simply to show if string "Staging" or "Production" inside the footer component.

1
  • I think you should have the __DEV__ variable accessible from any component in your application. Commented Jun 28, 2016 at 11:12

2 Answers 2

8

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")
})
Sign up to request clarification or add additional context in comments.

2 Comments

After using the plugin, how do I access the variable in a component? I tried console.log(Version) but Warning stated it was undefined.
I had to set "globals": { "ENV": false } in .eslintrc. :)
6

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.