Ilja
Ilja

Reputation: 46479

accessing environment variable from react component

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.

Upvotes: 9

Views: 11273

Answers (2)

HelloWorld101
HelloWorld101

Reputation: 4366

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/

Upvotes: 6

CD..
CD..

Reputation: 74096

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")
})

Upvotes: 8

Related Questions