React Component for Gitlab or Unleash Feature Flags
This library is deprecated since Unleash implemented a similar alternative and has an official Unleash SDK for React now. This official SDK also works with their Unleash proxy, which is the better solution in terms of security.
React component for Unleash or GitLab Feature Flags. This library provides a custom hook and react components to use in JavaScript or TypeScript projects.
Using NPM:
npm i --save react-unleash-flags
The following config is required in order to fetch te flags from your Unleash or GitLab instance:
host
instead)/client/features
) (this could be different if you want to point to an Unleash Proxy instead)This configuration can be provided as an env variabe. The environment variables are:
REACT_APP_FLAGS_CTX_APP_NAME
REACT_APP_FLAGS_CTX_HOST
REACT_APP_FLAGS_CTX_URL
(Deprecated! Use REACT_APP_FLAGS_CTX_HOST
instead)REACT_APP_FLAGS_CTX_URI
REACT_APP_FLAGS_CTX_INSTANCE_ID
The configuration can also be provide as a dict. (see examples below)
<FlagsProvider>
with config in env varsimport React from 'react';
import ReactDOM from 'react-dom';
import { FlagsProvider } from 'react-unleash-flags';
import App from './App';
const root = document.getElementById('root');
if (root != null) {
ReactDOM.render((
<FlagsProvider>
<App />
</FlagsProvider>
), cakeRoot);
}
<FlagsProvider>
with config in codeimport React from 'react';
import ReactDOM from 'react-dom';
import { FlagsProvider } from 'react-unleash-flags';
import App from './App';
const root = document.getElementById('root');
// we can also define the config in code instead of using env vars
const flagConfig = {
appName: 'production',
host: 'https://...',
uri: '/client/features',
instanceId: '...',
extraHttpHeaders: {
Authorization: 'token123'
}
};
// or if env vars are used for Unleash Flags settings, they can be combined
// these settings will be appended to the settings from the env variables
const flagConfig = {
extraHttpHeaders: {
Authorization: 'token123'
}
};
if (root != null) {
ReactDOM.render((
<FlagsProvider config={flagConfig} >
<App />
</FlagsProvider>
), cakeRoot);
}
Make sure you've setup the <FlagsProvider>
correctly.
useFlag
Hook// load the flag using the useFlag hook
const flag = useFlag(name);
// a flag that does not exist will return undefined
if (flag && flag.enabled) {
...
}
<FeatureFlag>
componentAttributes:
The <FeatureFlag>
component can handle both JSX and a function as child elements:
<FeatureFlag name="test-flag">
hello, this flag is enabled
</FeatureFlag>
<FeatureFlag name="test-flag" invert={true}>
hello, this flag is disabled
</FeatureFlag>
<FeatureFlag name="test-flag">
{(flag) => { console.log(flag); }}
</FeatureFlag>