DEV Community

Eduardo Oliveira
Eduardo Oliveira

Posted on

How to Hide Features from Production Environment in React

I writed, in brazilian portuguese, at Inventare, an article about testing into production with feature flag. Currently, we have an old project writed in React (create-react-app) with two environments, test (validation) and production and, in some cases, we need to hide some things from the production environment.

The project use env-cmd package to run the react scripts with different .env files to get the projects :

{
  ...
  "scripts" {
    "start": "env-cmd -f ./.env react-scripts start",
    "build": "env-cmd -f ./.env.production react-scripts build",
    "build:test": "env-cmd -f ./.env react-scripts build",
    ...
  }
  ...
}
Enter fullscreen mode Exit fullscreen mode

Then, into the .env and into the .env.production files we can add an variable:

# .env
...
REACT_APP_TEST_ENV=true
Enter fullscreen mode Exit fullscreen mode
# .env.production
...
REACT_APP_TEST_ENV=false
Enter fullscreen mode Exit fullscreen mode

Now, we can create an component to monitor this env variable and conditional render an element:

const TestOnly = ({ children }) => {
  const isTestingEnv = process.env.REACT_APP_TEST_ENV === 'true';

  if (!isTestingEnv) {
    return null;
  }
  return children;
};

export default TestOnly;
Enter fullscreen mode Exit fullscreen mode

Then, finally, we can encapsulates the feature with the <TestOnly /> component, for example:

return (
  <div>
    <TestOnly>
      <button>This is visible only in test env.</button>
    </TestOnly>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)