Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React JS: How can I export different components based on environment variable?

React JS code:

I want the src/app.jsx to do export default App when the REACT_APP_AUTH_SERVER variable in .env does not exist or have other value, and do export default withAuthenticator(App) when the REACT_APP_AUTH_SERVER variable in .env does exist, and has value aws-cognito:

src/app.jsx:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React, { Component } from 'react';
import SecuredGate from './SecuredGate/SecuredGate';
import { withAuthenticator } from '@aws-amplify/ui-react'
import './App.css';
import '../fontStyles.css';

class App extends Component {
  render() {
    return (
      <div>
        <SecuredGate />
      </div>
    );
  }
}

const Result = () => {
  if (process.env.REACT_APP_AUTH_SERVER && process.env.REACT_APP_AUTH_SERVER === "aws-cognito"){
    return withAuthenticator(App);
  } 
  return App;
}


// export default App;
// export default withAuthenticator(App)

export default Result;

However, this is not working.

If I do:

export default App;
// export default withAuthenticator(App)

, it works, and if I do:

// export default App;
export default withAuthenticator(App)

it works as well.

So what am I missing?

>Solution :

I think the problem is that the Result component returns a component instead of an element. To understand this better look at what App component does when called with <App />. It runs the code in its body and returns some markup. But what happens if you call <Result />. It will run the code in its block and return another component (a function). So to solve this you can try:

const Result = (process.env.REACT_APP_AUTH_SERVER && process.env.REACT_APP_AUTH_SERVER === "aws-cognito")
    ? withAuthenticator(App)
    : App;
}

export default Result;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading