Last active
February 11, 2019 04:27
-
-
Save j-/361bc272949fa78e5ce7152add1a8726 to your computer and use it in GitHub Desktop.
Render content conditionally using feature flag value detection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
// Feature flag storage | |
const features = new Map(); | |
features.set('editor', true); | |
features.set('sandbox', true); | |
features.set('env', 'sit1'); | |
// Some dummy feature | |
function Editor() { | |
return ( | |
<div>This is the editor feature</div> | |
); | |
} | |
// Some dummy feature | |
function Sandbox() { | |
return ( | |
<div>This is the sandbox feature</div> | |
); | |
} | |
// Context consumer | |
function Feature({ name, defaultValue = null, children }) { | |
const value = ( | |
features.has(name) ? | |
features.get(name) : | |
defaultValue | |
); | |
return children(value); | |
} | |
// Feature HOC | |
function feature(name, defaultValue = null) { | |
return function ({ children }) { | |
return ( | |
<Feature name={name} defaultValue={defaultValue}> | |
{children} | |
</Feature> | |
); | |
}; | |
} | |
// Feature equals value HOC | |
function featureValue(name, expected, defaultValue = null) { | |
return function ({ children }) { | |
return ( | |
<Feature name={name} defaultValue={defaultValue}> | |
{actual => actual === expected && children} | |
</Feature> | |
); | |
}; | |
} | |
// This HOC provides actual value as render prop | |
const SandboxFeature = feature('sandbox'); | |
// This HOC renders children when actual value matches given value | |
const EditorEnabled = featureValue('editor', true); | |
function App() { | |
return ( | |
<div className="App"> | |
<h1>Hello world</h1> | |
<Feature name="env" defaultValue="local"> | |
{env => `Connected to ${env}`} | |
</Feature> | |
<br /> | |
<Feature name="unset" defaultValue={false}> | |
{enabled => "This feature is " + (enabled ? "enabled" : "disabled")} | |
</Feature> | |
<SandboxFeature> | |
{enabled => enabled && <Sandbox />} | |
</SandboxFeature> | |
<EditorEnabled> | |
<Editor /> | |
</EditorEnabled> | |
</div> | |
); | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment