Skip to main content

React.js

npm version

warning

The SDK is currently in beta.

Installation

npm install @withgates/react-web

or

yarn add @withgates/react-web

First, create a Gates instance with your configuration:

import Gates from '@withgates/react-web';

const gates = new Gates('your-public-key', {});

Then wrap your application with the GateProvider:

import { GateProvider } from '@withgates/react-web';

function App() {
return (
<GateProvider gates={gates}>
<YourApp />
</GateProvider>
);
}

Hooks

useKnob

Knobs are basic kill-switches that allow you to quickly toggle features on and off. They provide a simple boolean value that can be used to control feature visibility.

The useKnob hook allows you to access the status of a knob in your component.

import { useKnob } from '@withgates/react-web';

function FeatureComponent() {
const isEnabled = useKnob('feature-key');

if (!isEnabled) {
return null;
}

return (
<div>
Your feature content here
</div>
);
}

useExperiment

The useExperiment hook allows you to access the status of an experiment in your component.

import { useExperiment } from '@withgates/react-web';

function FeatureComponent() {
const isEnabled = useExperiment('experiment-key');

if (!isEnabled) {
return null;
}

return (
<div>
Your experiment content here
</div>
);
}

Component Guards

KnobGuard

The KnobGuard component allows you to conditionally render a component based on the status of a knob.

import { KnobGuard } from '@withgates/react-web';

function App() {
return (
<KnobGuard value="feature-key">
<YourFeature />
</KnobGuard>
);
}

ExperimentGuard

The ExperimentGuard component allows you to conditionally render a component based on the status of an experiment.

import { ExperimentGuard } from '@withgates/react-web';

function App() {
return (
<ExperimentGuard value="experiment-key">
<YourExperiment />
</ExperimentGuard>
);
}

Instance Methods

The following methods are available on the Gates instance:

MethodParametersReturn TypeDescription
setUserAttributesattributes: Record<string, any>Promise<void>Sets custom attributes for the current user. These attributes can be used for targeting experiments. See Custom Attributes for more information.
signInUserappUserId: stringPromise<void>Signs in a user with the provided app user ID. This associates all future events and experiments with this user.
getUsernonePromise<any>Retrieves the current user information, including their attributes and assigned experiments.
initnonePromise<void>Initializes the Gates instance by loading stored gates from local storage and optionally syncing with the server. Should be called after creating a new Gates instance.
syncnonePromise<void>Syncs the gates from the server to the client. This should be called after the user has signed in.