Skip to content

Instantly share code, notes, and snippets.

@loopdream
Forked from sergiodxa/react-feature-flags.js
Created January 11, 2024 14:29
Show Gist options
  • Save loopdream/d73e90dc1444d7571528fa145bdccce2 to your computer and use it in GitHub Desktop.
Save loopdream/d73e90dc1444d7571528fa145bdccce2 to your computer and use it in GitHub Desktop.
React feature flags context, custom hook, hoc and render prop
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