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",
...
}
...
}
Then, into the .env
and into the .env.production
files we can add an variable:
# .env
...
REACT_APP_TEST_ENV=true
# .env.production
...
REACT_APP_TEST_ENV=false
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;
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>
);
Top comments (0)