React
If you're using React Native, check out the React Native SDK.
Install the latest version
Use your favorite package manager to install @prefab-cloud/prefab-cloud-react
npm | github
- npm
- yarn
npm install @prefab-cloud/prefab-cloud-react
yarn add @prefab-cloud/prefab-cloud-react
TypeScript types are included with the package.
Initialize the Client
This client includes a <PrefabProvider>
and usePrefab
hook.
First, wrap your component tree in the PrefabProvider
, e.g.
import { PrefabProvider } from "@prefab-cloud/prefab-cloud-react";
const WrappedApp = () => {
const onError = (reason) => {
console.error(reason);
};
return (
<PrefabProvider apiKey={"YOUR_CLIENT_API_KEY"} onError={onError}>
<MyApp />
</PrefabProvider>
);
};
If you wish for the user's browser to poll for updates to flags, you can pass a pollInterval
(in milliseconds) to the PrefabProvider
.
Feature Flags
Now use the usePrefab
hook to fetch flags. isEnabled
is a convenience method for boolean flags.
import { usePrefab } from "@prefab-cloud/prefab-cloud-react";
const Logo = () => {
const { isEnabled } = usePrefab();
if (isEnabled("new-logo")) {
return <img src={newLogo} className="App-logo" alt="logo" />;
}
return <img src={logo} className="App-logo" alt="logo" />;
};
You can also use get
to access flags with other data types.
const { get } = usePrefab();
const flagVlaue = get("my-string-flag");
Using Context
contextAttributes
lets you provide context that you can use to segment your users. Usually you will want to define context once when you setup PrefabProvider
.
import { PrefabProvider } from "@prefab-cloud/prefab-cloud-react";
const WrappedApp = () => {
const contextAttributes = {
user: { key: "abcdef", email: "jeffrey@example.com" },
subscription: { key: "adv-sub", plan: "advanced" },
};
const onError = (reason) => {
console.error(reason);
};
return (
<PrefabProvider
apiKey={"YOUR_CLIENT_API_KEY"}
contextAttributes={contextAttributes}
onError={onError}
>
<App />
</PrefabProvider>
);
};