React SDK
The @growth-rail/react package provides React hooks and context providers for integrating Growth Rail into React applications. Built on top of @growth-rail/core.
Installation
npm install @growth-rail/react @growth-rail/core
# or
yarn add @growth-rail/react @growth-rail/core
# or
pnpm add @growth-rail/react @growth-rail/core@growth-rail/react@2.1.1. Requires React 18+ and @growth-rail/core as a peer dependency.GrowthRailProvider
Wrap your application root with GrowthRailProvider. This initializes the SDK and makes all hooks available throughout your component tree.
import { GrowthRailProvider } from '@growth-rail/react';
function App() {
const { user } = useAuth(); // your auth hook
return (
<GrowthRailProvider
projectSecretKey={import.meta.env.VITE_GROWTH_RAIL_SECRET}
userId={user?.id} // optional: auto-calls initAppUser
debug={import.meta.env.DEV} // verbose logging in dev
cookieDomain=".yourapp.com" // optional: cross-subdomain
autoPageTrack={true} // optional: auto-detect referral codes
>
<YourApp />
</GrowthRailProvider>
);
}Provider Props
| Prop | Type | Required | Description |
|---|---|---|---|
projectSecretKey | string | Yes | Your project secret (sk_...). |
userId | string? | No | If provided, automatically calls initAppUser(userId) on mount. |
debug | boolean? | No | Enable verbose console logging. |
cookieDomain | string? | No | Domain for tracking cookies. |
autoPageTrack | boolean? | No | Auto-detect referral codes in the URL. |
userId: If your user is already authenticated when the provider mounts, pass their ID immediately. If they log in later, use the initAppUser() method from the hook instead.useGrowthRail Hook
The primary hook for interacting with Growth Rail. Available in any component wrapped by GrowthRailProvider.
import { useGrowthRail } from '@growth-rail/react';
function MyComponent() {
const {
initAppUser,
showReferralDashboard,
showFloatingButton,
hideFloatingButton,
getAttributionToken,
isLoading,
error,
} = useGrowthRail();
// ...
}Hook Return Values
| Property | Type | Description |
|---|---|---|
initAppUser(userId) | (id: string) => Promise<AppUserType> | Register a user and get their referral code/link. |
showReferralDashboard(options?) | (opts?) => void | Open the referral sharing modal/drawer. |
showFloatingButton(options) | (opts) => void | Show the floating trigger button. |
hideFloatingButton() | () => void | Remove the floating trigger button. |
getAttributionToken() | () => string | undefined | Get the opaque token for gr_attribution checkout metadata. |
isLoading | boolean | Whether an async operation is in progress. |
error | Error | null | Last error that occurred, or null. |
Usage Examples
Initialize user after login
import { useGrowthRail } from '@growth-rail/react';
export function LoginPage() {
const { initAppUser } = useGrowthRail();
const handleLogin = async (credentials) => {
const authUser = await loginService.login(credentials);
// Register with Growth Rail after successful login
await initAppUser(authUser.id);
};
return <LoginForm onSubmit={handleLogin} />;
}Track a reward event (Server-Side)
Reward tracking is handled server-side (or automatically via Stripe / RevenueCat integrations). Call the backend SDK endpoint when a user completes a qualifying event:
POST https://api.growthrail.dev/api/v1/sdk/track-reward-event
Header: x-project-secret-key: sk_live_xxx
{
"newUserId": "user_123",
"referralTrackingId": "tr_789",
"eventName": "user_signup"
}Show referral sharing UI
import { useGrowthRail } from '@growth-rail/react';
export function InvitePage() {
const { showReferralDashboard, showFloatingButton } = useGrowthRail();
return (
<div>
<h2>Invite Friends</h2>
<p>Share your referral link and earn rewards!</p>
<button onClick={() => showReferralDashboard()}>
Open Sharing Modal
</button>
<button onClick={() => showFloatingButton({ position: 'bottom-right' })}>
Show Floating Button
</button>
</div>
);
}Override modal options
showReferralDashboard({
title: 'Share & Earn!',
description: 'Invite friends to get 500 credits each.',
type: 'drawer',
theme: {
primaryColor: '#6366f1',
tintColor: '#000000',
backgroundColor: '#ffffff',
},
});ReferralDashboard Component
For embedding the referral dashboard directly in your page layout (instead of a modal/drawer overlay), use the ReferralDashboard component:
import { ReferralDashboard } from '@growth-rail/react';
export function ReferralsPage() {
return (
<div className="referrals-section">
<h2>Your Referral Program</h2>
<ReferralDashboard
title="Invite Friends"
appearance={{
primaryColor: '#6366f1',
backgroundColor: '#1e1e2e',
}}
onLinkCopied={() => toast.success('Referral link copied!')}
/>
</div>
);
}| Prop | Type | Description |
|---|---|---|
title | string? | Custom title override for the dashboard. |
appearance | ReferrerModalOptions? | Theme options (primaryColor, backgroundColor, etc.). |
onLinkCopied | () => void | Callback fired when the user copies their referral link. |
Complete Example
import { GrowthRailProvider, useGrowthRail } from '@growth-rail/react';
// 1. Wrap your app
function App() {
return (
<GrowthRailProvider
projectSecretKey={import.meta.env.VITE_GROWTH_RAIL_SECRET}
debug={import.meta.env.DEV}
autoPageTrack={true}
>
<Router>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/signup-complete" element={<SignupComplete />} />
</Routes>
</Router>
</GrowthRailProvider>
);
}
// 2. Register users after login
function LoginPage() {
const { initAppUser } = useGrowthRail();
const onLogin = async (userId: string) => {
await initAppUser(userId);
navigate('/dashboard');
};
return <LoginForm onSubmit={onLogin} />;
}
// 3. Show referral UI on dashboard
function Dashboard() {
const { showReferralDashboard } = useGrowthRail();
return (
<div>
<h1>Dashboard</h1>
<button onClick={() => showReferralDashboard()}>
Invite Friends
</button>
</div>
);
}
// 4. Track rewards (Server-Side or Webhook)
// Call POST /api/v1/sdk/track-reward-event from your backend after signup/purchase, or let Stripe/RevenueCat handle attribution automatically.Error Handling
The hook exposes an error state for catching issues:
const { error, isLoading, initAppUser } = useGrowthRail();
useEffect(() => {
if (error) {
// Show toast, log to error tracker, etc.
}
}, [error]);