Created
October 24, 2019 17:55
-
-
Save sergiodxa/0a7567ab453449467640a030be6484f8 to your computer and use it in GitHub Desktop.
React feature flags context, custom hook, hoc and render prop
This file contains 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"; | |
const FeatureFlags = React.createContext(null); | |
export function FeatureProvider({ features = null, children }) { | |
if (features === null || typeof features !== "object") { | |
throw new TypeError("The features prop must be an object or an array."); | |
} | |
return ( | |
<FeatureFlags.Provider value={features}>{children}</FeatureFlags.Provider> | |
); | |
} | |
// Custom Hook API | |
export function useFeature(name) { | |
const features = React.useContext(FeatureFlags); | |
if (features === null) { | |
throw new Error("You must wrap your components in a FeatureProvider."); | |
} | |
return Array.isArray(features) ? features.includes(name) : features[name]; | |
} | |
// High Order Component API | |
export function feature(featureName) { | |
return Component => props => { | |
const hasFeature = useFeature(featureName); | |
if (!hasFeature) return null; | |
return <Component {...props} />; | |
}; | |
} | |
// Render Prop API | |
export function Feature({ name, children, render = children }) { | |
const hasFeature = useFeature(name); | |
if (typeof render === "function") return render({ [name]: hasFeature }); | |
if (!hasFeature) return null; | |
return render; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment