### Install and Build React Facebook
Source: https://github.com/seeden/react-facebook/blob/main/CONTRIBUTING.md
Clone the repository, install dependencies, build the package, and start the documentation server.
```bash
git clone https://github.com/YOUR_USERNAME/react-facebook.git
cd react-facebook
npm install
npm run build
npm run dev:docs
```
--------------------------------
### Install React Facebook SDK
Source: https://github.com/seeden/react-facebook/blob/main/README.md
Install the react-facebook package using npm.
```bash
npm install react-facebook
```
--------------------------------
### ShareButton Usage Examples
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/share-button.mdx
Examples demonstrating how to use the ShareButton component with different configurations.
```APIDOC
## Usage
### Basic
```tsx
Share this page
```
### Styled with Tailwind CSS
```tsx
Share on Facebook
```
### Custom Element
```tsx
Share this article
```
```
--------------------------------
### Facebook Pixel Tracking Setup
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/getting-started.mdx
This example shows how to enable Facebook Pixel tracking by providing a `pixelId` to the `FacebookProvider`. It includes functions to track page views and custom events like 'Purchase'. Replace 'YOUR_APP_ID' and 'YOUR_PIXEL_ID' with your actual IDs.
```tsx
import { FacebookProvider, usePixel } from 'react-facebook';
function App() {
return (
);
}
function TrackingExample() {
const { track, pageView } = usePixel();
return (
);
}
```
--------------------------------
### Install react-facebook
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/migration/facebook-pixel-setup.mdx
Instructions for uninstalling the old react-facebook-pixel package and installing the new react-facebook package using npm.
```bash
npm uninstall react-facebook-pixel
npm install react-facebook
```
--------------------------------
### First Login Component Example
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/getting-started.mdx
Render a basic Login component after setting up the FacebookProvider. This example shows how to handle successful logins and errors, and specifies the requested scopes for user permissions.
```tsx
import { FacebookProvider, Login } from 'react-facebook';
function App() {
return (
{
console.log('Logged in:', response.authResponse.accessToken);
}}
onError={(error) => {
console.error('Login failed:', error);
}}
scope={['public_profile', 'email']}
>
Login with Facebook
);
}
```
--------------------------------
### Basic Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/like.mdx
A simple example of how to use the Like component with the required `href` prop.
```APIDOC
## Usage
### Basic
```tsx
```
```
--------------------------------
### Feature Request Template - Example Usage
Source: https://github.com/seeden/react-facebook/blob/main/CONTRIBUTING.md
Example of how a proposed new feature might be used within a React component, demonstrating prop usage and event handling.
```typescript
// Example usage
```
--------------------------------
### Tracking Events with usePixel
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/pixel-provider.mdx
Example demonstrating how to use the usePixel hook to track events and manage consent.
```APIDOC
### Tracking Events
```tsx
import { usePixel } from 'react-facebook';
function CheckoutButton() {
const { track, grantConsent, revokeConsent } = usePixel();
const handlePurchase = () => {
track('Purchase', {
value: 29.99,
currency: 'USD',
content_name: 'Premium Plan',
});
};
return (
);
}
```
```
--------------------------------
### Install react-facebook with Yarn
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/getting-started.mdx
Use Yarn to install the react-facebook package. Yarn is an alternative package manager for JavaScript.
```bash
yarn add react-facebook
```
--------------------------------
### Advanced Usage Examples
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/like.mdx
Demonstrates various configurations of the Like component, including different layouts, options for showing faces, color schemes, and sizes.
```APIDOC
### With Layout and Faces
```tsx
```
### Dark Color Scheme
```tsx
```
### Box Count Layout
```tsx
```
```
--------------------------------
### Install react-facebook and Uninstall react-facebook-login
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/migration/facebook-login-setup.mdx
Commands to uninstall the legacy react-facebook-login package and install the current react-facebook library. This is part of the migration process.
```bash
npm uninstall react-facebook-login @types/react-facebook-login
npm install react-facebook
```
--------------------------------
### Error Handling
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/use-pixel.mdx
Provides an example of how to check the `loading` and `error` states returned by `usePixel` to manage the UI.
```typescript
import { usePixel } from 'react-facebook';
function TrackingStatus() {
const { loading, error } = usePixel();
if (loading) return
Loading pixel...
;
if (error) return
Pixel unavailable: {error.message}
;
return
Pixel active
;
}
```
--------------------------------
### Facebook SDK Integration Example
Source: https://github.com/seeden/react-facebook/blob/main/CONTRIBUTING.md
Example of integrating with the Facebook SDK within a React component, including checking SDK availability and handling UI actions like sharing.
```typescript
// Example SDK integration pattern
export default function MyFacebookComponent() {
const { api, isLoading } = useFacebook();
const handleAction = useCallback(async () => {
if (!api) {
console.warn('Facebook SDK not available');
return;
}
try {
const response = await api.ui({
method: 'share',
href: 'https://example.com',
});
console.log('Share successful:', response);
} catch (error) {
console.error('Share failed:', error);
}
}, [api]);
if (isLoading) {
return
Loading Facebook SDK...
;
}
return ;
}
```
--------------------------------
### Install react-facebook with pnpm
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/getting-started.mdx
Use pnpm to install the react-facebook package. pnpm is a performant package manager that saves disk space.
```bash
pnpm add react-facebook
```
--------------------------------
### Next.js App Router Full Setup with Providers
Source: https://context7.com/seeden/react-facebook/llms.txt
This setup configures Facebook SDK, Pixel, and error handling for the Next.js App Router. Ensure your NEXT_PUBLIC_FB_APP_ID and NEXT_PUBLIC_FB_PIXEL_ID environment variables are set. The SDK load is deferred until the first user interaction when 'lazy' is true.
```tsx
'use client';
import { FacebookProvider, FacebookErrorBoundary } from 'react-facebook';
export default function Providers({ children }: { children: React.ReactNode }) {
return (
Facebook features are currently unavailable.}
>
{children}
);
}
```
```tsx
import Providers from './providers';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Commit Message Examples
Source: https://github.com/seeden/react-facebook/blob/main/CONTRIBUTING.md
Follow this format for clear and descriptive commit messages, including how to denote breaking changes.
```bash
# Good examples
git commit -m "Add FacebookPixel component with tracking support"
git commit -m "Fix useLogin hook memory leak on unmount"
git commit -m "Update LoginButton component to support custom render"
git commit -m "Add comprehensive tests for Share component"
# Include breaking changes
git commit -m "BREAKING: Remove deprecated render prop from FacebookLogin"
```
--------------------------------
### Initialize Facebook SDK with FacebookProvider
Source: https://context7.com/seeden/react-facebook/llms.txt
Wrap your application or relevant subtrees with FacebookProvider to load the SDK and provide context. Configure SDK initialization options and optionally set a pixelId for automatic FacebookPixelProvider setup.
```tsx
import { FacebookProvider } from 'react-facebook';
// Basic setup — wrap your app (or the subtree that needs FB features)
export default function App({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
```tsx
// Next.js App Router — create a client-component wrapper
// app/providers.tsx
'use client';
import { FacebookProvider } from 'react-facebook';
export default function Providers({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
// app/layout.tsx
import Providers from './providers';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
```tsx
// Next.js Pages Router — app/pages/_app.tsx
import type { AppProps } from 'next/app';
import { FacebookProvider } from 'react-facebook';
export default function MyApp({ Component, pageProps }: AppProps) {
return (
);
}
```
--------------------------------
### Forward Token to Server
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-login.mdx
After a successful login, this example shows how to send the obtained access token and user ID to a backend API for server-side verification or session creation.
```tsx
import { useLogin } from 'react-facebook';
function LoginWithBackend() {
const { login, loading } = useLogin();
const [authenticated, setAuthenticated] = useState(false);
const handleLogin = async () => {
try {
const response = await login({ scope: 'email,public_profile' });
if (response.status !== 'connected' || !response.authResponse) {
throw new Error('Login did not complete');
}
const { accessToken, userID } = response.authResponse;
// Send the access token to your backend for verification
const res = await fetch('/api/auth/facebook', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accessToken, userID }),
});
if (!res.ok) {
throw new Error('Server authentication failed');
}
const session = await res.json();
console.log('Session created:', session);
setAuthenticated(true);
} catch (err) {
console.error('Authentication error:', err);
}
};
if (authenticated) {
return
Successfully authenticated!
;
}
return (
);
}
```
--------------------------------
### Standalone Pixel Tracking Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/pixel-provider.mdx
Example of how to use FacebookPixelProvider for standalone Pixel tracking.
```APIDOC
## Usage
### Standalone Pixel Tracking
```tsx
import { FacebookPixelProvider } from 'react-facebook';
function App({ children }) {
return {children};
}
```
```
--------------------------------
### Advanced Matching Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/pixel-provider.mdx
Example of configuring advanced matching with FacebookPixelProvider.
```APIDOC
### With Advanced Matching
```tsx
{children}
```
```
--------------------------------
### Direct fbq Access
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/use-pixel.mdx
Demonstrates using the `fbq` function for advanced use cases, such as calling `trackSingle` for multi-pixel setups.
```typescript
import { usePixel } from 'react-facebook';
function AdvancedTracking() {
const { fbq } = usePixel();
const handleClick = async () => {
// Track a single pixel (multi-pixel setup)
await fbq('trackSingle', 'PIXEL_ID_2', 'Lead', { value: 50 });
};
return ;
}
```
--------------------------------
### Complete Auth Flow with React Facebook Hooks
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/getting-started.mdx
This example demonstrates a full authentication flow using `useLogin`, `useProfile`, and `useLoginStatus` hooks. It handles user login, displays profile information, and provides a logout option. Ensure you replace 'YOUR_APP_ID' with your actual Facebook App ID.
```tsx
import { FacebookProvider, useLogin, useProfile, useLoginStatus } from 'react-facebook';
function AuthFlow() {
const { status } = useLoginStatus();
const { login, logout, loading: isLoggingIn } = useLogin();
const { profile, loading: isLoadingProfile } = useProfile(['name', 'email', 'picture']);
if (status === 'connected' && profile) {
return (
{profile.name}
{profile.email}
);
}
return (
);
}
function App() {
return (
);
}
```
--------------------------------
### PR Template Example
Source: https://github.com/seeden/react-facebook/blob/main/CONTRIBUTING.md
Use this markdown template when submitting a Pull Request. It covers essential checks for description, change type, testing, and documentation.
```markdown
## Description
Brief description of changes
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
- [ ] Added/updated tests
- [ ] All tests pass
- [ ] Tested with real Facebook integration
## Documentation
- [ ] Updated README
- [ ] Updated API docs
- [ ] Added examples
## Checklist
- [ ] Self-review completed
- [ ] TypeScript types updated
- [ ] No breaking changes (or properly documented)
```
--------------------------------
### Consent-First Setup with LocalStorage Persistence
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/consent.mdx
Ensures no data is sent before user consent by revoking consent immediately on load and granting it only after explicit user action. Uses localStorage to persist the consent state.
```tsx
import { usePixel } from 'react-facebook';
import { useEffect } from 'react';
function ConsentGate({ children }: { children: React.ReactNode }) {
const { revokeConsent, grantConsent, loading } = usePixel();
useEffect(() => {
// Revoke consent as soon as pixel loads
if (!loading) {
const hasConsent = localStorage.getItem('fb-pixel-consent') === 'granted';
if (hasConsent) {
grantConsent();
} else {
revokeConsent();
}
}
}, [loading, grantConsent, revokeConsent]);
const handleAccept = async () => {
localStorage.setItem('fb-pixel-consent', 'granted');
await grantConsent();
};
const handleDecline = async () => {
localStorage.setItem('fb-pixel-consent', 'revoked');
await revokeConsent();
};
return (
<>
{children}
>
);
}
```
--------------------------------
### Standalone Pixel Tracking Setup
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/pixel-provider.mdx
Set up the FacebookPixelProvider with your unique Pixel ID to enable tracking. This component should wrap the part of your application that requires Pixel functionality.
```tsx
function App({ children }) {
return {children};
}
```
--------------------------------
### Share Link to Feed with Preview
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-feed.mdx
An example of sharing a link to the user's feed with a preview image, name, caption, and description. It includes error handling and displays loading states.
```tsx
import { useFeed } from 'react-facebook';
function ShareLinkToFeed() {
const { feed, loading, error } = useFeed();
const handlePost = async () => {
try {
const response = await feed({
from: 'me',
to: 'me',
link: 'https://example.com/blog/my-article',
picture: 'https://example.com/images/article-cover.jpg',
name: 'My Latest Article',
caption: 'example.com',
description: 'Check out this article about building React apps with the Facebook SDK.',
});
console.log('Feed dialog response:', response);
} catch (err) {
console.error('Feed post failed:', err);
}
};
return (
{error &&
Error: {error.message}
}
);
}
```
--------------------------------
### TypeScript: Fetching User Photos with Graph API
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/index.mdx
Shows how to use the `useGraphAPI` hook for fetching user photos with typed responses. This example demonstrates fetching 'id', 'source', and 'name' fields for up to 10 photos from the '/me/photos' endpoint. It includes loading and error state handling.
```tsx
import type { LoginResponse, AuthResponse, UseGraphAPIReturn } from 'react-facebook';
import { useGraphAPI } from 'react-facebook';
interface Photo {
id: string;
source: string;
name: string;
}
function PhotoGallery() {
const { data, loading, error } = useGraphAPI<{ data: Photo[] }>({
path: '/me/photos',
params: { fields: 'id,source,name', limit: 10 },
autoFetch: true,
});
if (loading) return
Loading photos...
;
if (error) return
Error: {error.message}
;
return (
{data?.data.map((photo) => (
))}
);
}
```
--------------------------------
### Basic Usage of useShare
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-share.mdx
Use the useShare hook to get the share function, loading state, and error state. Call the share function with required options like href and display.
```tsx
function ShareComponent() {
const { share, loading, error } = useShare();
const handleShare = () => {
share({
href: 'https://example.com',
display: 'popup',
hashtag: '#example',
});
};
return (
);
}
```
--------------------------------
### Track Purchase Event with usePixel Hook
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/index.mdx
Use the `usePixel` hook within a child component to fire events after the provider is set up. This example shows how to track a 'Purchase' event with associated value and currency.
```tsx
import { usePixel } from 'react-facebook';
function CheckoutButton() {
const { track } = usePixel();
return ;
}
```
--------------------------------
### Manual SDK Initialization (Lazy Loading)
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-facebook.mdx
Illustrates how to use the `lazy: true` option with `useFacebook` to defer SDK initialization until a user action, improving initial page load performance.
```APIDOC
## Manual SDK Initialization
### Description
Use the `lazy` option to defer SDK initialization until a user action. This is useful when you want to reduce initial page load time or only load the SDK when actually needed.
### Code
```tsx
import { useFacebook } from 'react-facebook';
import { useState } from 'react';
function LazyFacebookInit() {
const { api, init, loading, error } = useFacebook({ lazy: true });
const [initialized, setInitialized] = useState(false);
const handleInit = async () => {
try {
const facebook = await init();
if (facebook) {
console.log('SDK initialized. App ID:', facebook.getAppId());
setInitialized(true);
}
} catch (err) {
console.error('SDK initialization failed:', err);
}
};
if (error) {
return
SDK Error: {error.message}
;
}
if (!initialized) {
return (
);
}
return
Facebook SDK is ready (App ID: {api?.getAppId()})
;
}
```
```
--------------------------------
### Lazy Initialization
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/use-pixel.mdx
Shows how to enable lazy initialization by passing the `lazy` option to `usePixel`, requiring manual calls to `init()`.
```typescript
import { usePixel } from 'react-facebook';
function CookieBanner() {
const { init } = usePixel({ lazy: true });
return ;
}
```
--------------------------------
### FacebookPixelProvider for Pixel-Only Setup
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/migration/facebook-pixel-setup.mdx
Use FacebookPixelProvider for Pixel tracking without the full Facebook SDK. This setup allows for debugging and direct pixel ID configuration.
```tsx
import { FacebookPixelProvider, usePixel } from 'react-facebook';
function App() {
return (
);
}
```
--------------------------------
### Equivalent to Manual PageView on Mount
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/use-page-view.mdx
This demonstrates the equivalent manual implementation of firing a PageView event on mount using `usePixel` and `useEffect`.
```tsx
const { pageView } = usePixel();
useEffect(() => {
pageView();
}, []);
```
--------------------------------
### Manual SDK Initialization with Lazy Loading
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-facebook.mdx
Utilize the `lazy: true` option with useFacebook to defer SDK initialization. Manually call the `init()` function in response to user actions, such as a button click, to load the SDK only when needed.
```tsx
import { useFacebook } from 'react-facebook';
import { useState } from 'react';
function LazyFacebookInit() {
const { api, init, loading, error } = useFacebook({ lazy: true });
const [initialized, setInitialized] = useState(false);
const handleInit = async () => {
try {
const facebook = await init();
if (facebook) {
console.log('SDK initialized. App ID:', facebook.getAppId());
setInitialized(true);
}
} catch (err) {
console.error('SDK initialization failed:', err);
}
};
if (error) {
return
SDK Error: {error.message}
;
}
if (!initialized) {
return (
);
}
return
Facebook SDK is ready (App ID: {api?.getAppId()})
;
}
```
--------------------------------
### FacebookProvider with All Options
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/facebook-provider.mdx
Configure the FacebookProvider with all available SDK initialization options. This allows for fine-grained control over how the Facebook SDK behaves.
```tsx
{children}
```
--------------------------------
### Debug Mode Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/pixel-provider.mdx
Example of enabling debug mode for the FacebookPixelProvider.
```APIDOC
### With Debug Mode
```tsx
{children}
```
```
--------------------------------
### Basic FacebookProvider Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/facebook-provider.mdx
Initialize the Facebook SDK by wrapping your application's root component with FacebookProvider. Ensure you replace 'YOUR_APP_ID' with your actual Facebook App ID.
```tsx
import { FacebookProvider } from 'react-facebook';
export default function App({ children }) {
return {children};
}
```
--------------------------------
### Share Component Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/share.mdx
Demonstrates how to import and use the Share component with different props for layout and size.
```APIDOC
## Import
```tsx
import { Share } from 'react-facebook';
```
## Props
| Prop | Type | Default | Description |
| ----------- | ---------------------------------------------------------- | ---------------- | ----------------------------------------------------- |
| `href` | `string` | Current page URL | The URL to share. |
| `layout` | `'box_count' | 'button_count' | 'button' | 'icon_link'` | `'icon_link'` | Layout style for the share button. |
| `size` | `'small' | 'large'` | `'small'` | Button size. |
| `lazy` | `boolean` | `false` | Lazy-load the plugin. |
| `className` | `string` | `''` | Additional CSS class names appended to the container. |
## Usage
### Basic
```tsx
```
### Large Button with Count
```tsx
```
### Box Count Layout
```tsx
```
```
--------------------------------
### Import Only Necessary Components
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/advanced/performance.mdx
Import only the components and hooks you need from the main entry point to leverage tree shaking and minimize bundle size. Avoid importing from deep paths.
```tsx
// Good -- only imports what you use
import { FacebookProvider, useLogin, useProfile } from 'react-facebook';
// Also good -- named imports from the same entry point
import { Login, Like } from 'react-facebook';
```
--------------------------------
### Auto-fetch on mount
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-graph-api.mdx
By default, useGraphAPI fetches data as soon as the component mounts. This example shows fetching a list of friends.
```APIDOC
## Auto-fetch on mount
By default, `useGraphAPI` fetches data as soon as the component mounts.
```tsx
function MyFriends() {
const { data, loading, error } = useGraphAPI({
path: '/me/friends',
params: { limit: 10 },
});
if (loading) return
Loading...
;
if (error) return
Error: {error.message}
;
return (
{data?.data?.map((f) => (
{f.name}
))}
);
}
```
```
--------------------------------
### Importing useFeed and useSend Hooks
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/migration/v10-to-v11.mdx
Demonstrates importing the `useFeed` and `useSend` hooks, which are now exported from the main entry point of the library.
```tsx
import { useFeed, useSend } from 'react-facebook';
```
--------------------------------
### Share with Hashtag using useShare
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-share.mdx
Include a hashtag with the shared content by providing the hashtag option. The hashtag must start with '#'.
```tsx
import { useShare } from 'react-facebook';
function ShareWithHashtag() {
const { share, loading } = useShare();
const handleShare = async () => {
try {
await share({
href: 'https://example.com/summer-sale',
display: 'popup',
hashtag: '#SummerSale',
});
} catch (err) {
console.error('Share cancelled or failed:', err);
}
};
return (
);
}
```
--------------------------------
### Using transform
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-graph-api.mdx
The `transform` option allows you to reshape the API response before it is stored in the `data` state. This example extracts the total friend count.
```APIDOC
## Using transform
The `transform` option lets you reshape the API response before it is stored in `data`.
```tsx
function FriendCount() {
const { data, loading } = useGraphAPI({
path: '/me/friends',
transform: (response) => response.summary?.total_count ?? 0,
});
if (loading) return
Loading...
;
return
You have {data} friends.
;
}
```
```
--------------------------------
### Pages Router: Setup FacebookProvider in _app.tsx
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/advanced/ssr.mdx
For Next.js Pages Router, configure FacebookProvider within the _app.tsx file to wrap your entire application.
```tsx
// pages/_app.tsx
import type { AppProps } from 'next/app';
import { FacebookProvider } from 'react-facebook';
export default function App({ Component, pageProps }: AppProps) {
return (
);
}
```
--------------------------------
### Basic Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-facebook.mdx
Demonstrates the basic usage of the `useFacebook` hook to access the Facebook SDK instance and its state.
```APIDOC
## Basic Usage
### Description
This example shows how to use the `useFacebook` hook to get the Facebook SDK instance and handle loading and error states.
### Code
```tsx
import { useFacebook } from 'react-facebook';
function MyComponent() {
const { api, loading, error } = useFacebook();
if (loading) return
Loading Facebook SDK...
;
if (error) return
Error: {error.message}
;
return
Facebook SDK ready! App ID: {api?.getAppId()}
;
}
```
```
--------------------------------
### Eager Facebook SDK Loading
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/advanced/performance.mdx
The default behavior where the Facebook SDK script starts loading immediately upon the `FacebookProvider` component mounting.
```tsx
// SDK script starts loading immediately on mount
```
--------------------------------
### Page Component Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/page.mdx
Demonstrates how to import and use the Page component with different configurations.
```APIDOC
## Import
```tsx
import { Page } from 'react-facebook';
```
## Props
| Prop | Type | Default | Description |
| --------------------- | ------------------ | ---------------- | ---------------------------------------------------------------------------------------- |
| `href` | `string` | Current page URL | The URL of the Facebook Page. |
| `tabs` | `string` | `undefined` | Comma-separated list of tabs to render. Options: `'timeline'`, `'events'`, `'messages'`. |
| `width` | `number | string` | `undefined` | Width of the plugin in pixels (min `180`, max `500`). |
| `height` | `number | string` | `undefined` | Height of the plugin in pixels (min `70`). |
| `hideCover` | `boolean` | `false` | Hide the cover photo in the header. |
| `showFacepile` | `boolean` | `false` | Show profile photos of friends who like the page. |
| `hideCTA` | `boolean` | `false` | Hide the custom call-to-action button (if available). |
| `smallHeader` | `boolean` | `false` | Use a smaller header. |
| `adaptContainerWidth` | `boolean` | `false` | Adapt the plugin width to its parent container. |
| `lazy` | `boolean` | `false` | Lazy-load the plugin. |
| `className` | `string` | `''` | Additional CSS class names appended to the container. |
## Usage Examples
### Basic
```tsx
```
### Timeline with Facepile
```tsx
```
### Multiple Tabs
```tsx
```
### Minimal
```tsx
```
```
--------------------------------
### FacebookProvider with Facebook Pixel
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/facebook-provider.mdx
Integrate Facebook Pixel tracking by providing your pixel ID directly to the FacebookProvider. This simplifies setup for basic pixel functionality.
```tsx
{children}
```
--------------------------------
### Basic PageView Tracking on Mount
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/use-page-view.mdx
The simplest usage fires a PageView event when the component mounts. This is the default behavior.
```tsx
import { usePageView } from 'react-facebook';
function ProductPage() {
usePageView();
return
Product details...
;
}
```
--------------------------------
### Upgrade react-facebook Package
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/migration/v10-to-v11.mdx
Install the latest version of the react-facebook package using npm. This command updates your project to the newest version, enabling all new features and improvements.
```bash
npm install react-facebook@latest
```
--------------------------------
### Initialize ReactPixel Imperatively
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/migration/facebook-pixel-setup.mdx
Initialize the ReactPixel library once in your application's entry point. This method is SSR-safe and does not require a React context.
```tsx
import { ReactPixel } from 'react-facebook';
// Initialize once (e.g., in your app entry point)
ReactPixel.init('YOUR_PIXEL_ID');
// Track events anywhere
ReactPixel.pageView();
ReactPixel.track('Purchase', { value: 29.99, currency: 'USD' });
ReactPixel.trackCustom('ButtonClick', { button: 'hero-cta' });
```
--------------------------------
### Manual Page View Event Trigger
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/use-page-view.mdx
The returned `pageView` function allows you to manually fire a PageView event at any point, for example, when a specific user action occurs.
```tsx
function Wizard() {
const { pageView } = usePageView({ trackOnMount: false });
const handleStepChange = (step: number) => {
// Track each wizard step as a page view
pageView();
};
return ;
}
```
--------------------------------
### Handle Facebook Login and Fetch Profile with Hooks
Source: https://github.com/seeden/react-facebook/blob/main/README.md
Use `useLogin` for programmatic login/logout and `useProfile` to fetch user details like name, email, and picture. The `login` function accepts scopes, and `useProfile` takes an array of fields to retrieve. Requires `FacebookProvider`.
```tsx
import { useLogin, useProfile } from 'react-facebook';
function AuthFlow() {
const { login, logout, loading } = useLogin();
const { profile } = useProfile(['name', 'email', 'picture']);
if (profile) {
return (
Welcome, {profile.name}
);
}
return (
);
}
```
--------------------------------
### Type-Safe Subscription with useSubscribe
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-subscribe.mdx
Utilize the generic type parameter of useSubscribe to provide type safety for event data. This example defines an interface for the login response and uses it with the hook.
```tsx
import { useSubscribe } from 'react-facebook';
interface LoginResponse {
status: 'connected' | 'not_authorized' | 'unknown' | 'authorization_expired';
authResponse?: {
accessToken: string;
userID: string;
expiresIn: number;
signedRequest: string;
};
}
function TypedAuthListener() {
const lastLogin = useSubscribe('auth.statusChange', (response) => {
if (response.status === 'connected' && response.authResponse) {
console.log('User connected. Token:', response.authResponse.accessToken);
} else {
console.log('User status:', response.status);
}
});
return (
Auth Status Monitor
{lastLogin ? (
Status:{' '}
{lastLogin.status}
{lastLogin.authResponse && (
User ID: {lastLogin.authResponse.userID}
)}
) : (
Waiting for auth event...
)}
);
}
```
--------------------------------
### Basic Usage of useFacebook
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/hooks/use-facebook.mdx
Use the useFacebook hook to get the Facebook SDK API instance, loading, and error states. Handle loading and error states before accessing the API.
```tsx
function MyComponent() {
const { api, loading, error } = useFacebook();
if (loading) return
Loading Facebook SDK...
;
if (error) return
Error: {error.message}
;
return
Facebook SDK ready! App ID: {api?.getAppId()}
;
}
```
--------------------------------
### Initialize Pixel via Standalone FacebookPixelProvider
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/index.mdx
Use `FacebookPixelProvider` directly if you only need pixel tracking without the full Facebook SDK. This offers a smaller footprint. Ensure you provide your `pixelId`.
```tsx
import { FacebookPixelProvider } from 'react-facebook';
function App() {
return (
);
}
```
--------------------------------
### Basic Consent Handling with usePixel Hook
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/pixel/consent.mdx
Demonstrates the basic usage of grantConsent and revokeConsent from the usePixel hook within a cookie banner component. Requires FacebookProvider setup with appId and pixelId.
```tsx
import { FacebookProvider, usePixel } from 'react-facebook';
function CookieBanner() {
const { grantConsent, revokeConsent } = usePixel();
return (
We use cookies to measure advertising effectiveness.
);
}
function App() {
return (
);
}
```
--------------------------------
### Initialize ReactPixel with Advanced Matching
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/migration/facebook-pixel-setup.mdx
Initialize ReactPixel with advanced user matching parameters like email, first name, and last name. Also configures autoConfig and debug modes.
```tsx
ReactPixel.init(
'YOUR_PIXEL_ID',
{
em: 'user@example.com',
fn: 'john',
ln: 'doe',
},
{
autoConfig: true,
debug: false,
},
);
```
--------------------------------
### Lazy Initialization with Pixel Provider
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/pixel-provider.mdx
Use the `lazy` prop to defer loading the Pixel script until the first tracking call is made. This can improve initial page load performance.
```tsx
{children}
```
--------------------------------
### useLocale
Source: https://github.com/seeden/react-facebook/blob/main/README.md
Enables dynamic language switching without requiring a page reload.
```APIDOC
## useLocale
### Description
Enables dynamic language switching without requiring a page reload.
### Method Signature
useLocale()
### Returns
An object containing `locale`, `setLocale`, and `isChangingLocale`.
### Example
```tsx
import { useLocale } from 'react-facebook';
function LocaleSwitcher() {
const { locale, setLocale, isChangingLocale } = useLocale();
return (
);
}
```
```
--------------------------------
### Comments Component Usage
Source: https://github.com/seeden/react-facebook/blob/main/apps/docs/content/docs/components/comments.mdx
Demonstrates how to import and use the Comments component with different configuration options.
```APIDOC
## Import
```tsx
import { Comments } from 'react-facebook';
```
## Props
| Prop | Type | Default | Description |
| ------------- | -------------------------- | ---------------- | ------------------------------------------------------------- |
| `href` | `string` | Current page URL | The URL for which comments are displayed. |
| `numPosts` | `number` | `undefined` | Number of comments to show by default. |
| `orderBy` | `'reverse_time' | 'time'` | `undefined` | Comment ordering. `'reverse_time'` shows newest first. |
| `width` | `number | string` | `undefined` | Width of the plugin in pixels or as a string (e.g. `'100%'`). |
| `colorScheme` | `'light' | 'dark'` | `undefined` | Color scheme for the plugin. |
| `mobile` | `boolean` | `false` | Force the mobile-optimized version. |
| `lazy` | `boolean` | `false` | Lazy-load the plugin. |
| `className` | `string` | `''` | Additional CSS class names appended to the container. |
## Usage Examples
### Basic
```tsx
```
### With Options
```tsx
```
### Dark Theme
```tsx
```
### Mobile Optimized
```tsx
```
```