Modern, TypeScript-ready, and feature-complete React components for Facebook integration
- Complete Facebook SDK integration - Like, Share, Comments, Videos, Login, and more
- Modern React patterns - Built with TypeScript, React Hooks, and children as function pattern
- Dynamic locale support - Change Facebook widget language on-the-fly without page reload
- Facebook Pixel integration - Built-in conversion tracking, analytics, and GDPR compliance
- Flexible styling - Works with any CSS framework (Tailwind, styled-components, etc.)
- Tree-shakeable - Import only what you need for optimal bundle size
- Async initialization - Proper lazy loading with error handling and retry logic
- ✨ v10.0.1 Updates - Unified Login component, removed deprecated features, improved locale handling
npm install react-facebook
# or
yarn add react-facebook
# or
pnpm add react-facebook📖 Interactive Documentation - Live examples, playground, and complete API reference
Our documentation site includes:
- Live Playground - Test components with your own Facebook App ID
- Interactive Examples - Modify props and see results instantly
- Complete API Reference - All components, hooks, and props documented
- Copy-paste Examples - Ready-to-use code snippets
- Real Facebook Integration - All examples work with actual Facebook APIs
import { FacebookProvider, Login } from 'react-facebook';
function App() {
  return (
    <FacebookProvider appId="YOUR_APP_ID">
      <Login
        onSuccess={(response) => console.log('Login success:', response)}
        onError={(error) => console.error('Login failed:', error)}
        className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700"
      >
        Login with Facebook
      </Login>
    </FacebookProvider>
  );
}- Available Components
- Core Components
- Authentication
- Social Features
- Advanced Features
- Facebook Pixel
- Advanced Usage
- FAQ
⚠️ v10.0.1 Breaking Changes: Removed deprecated Facebook components (CustomChat, MessageUs, MessengerCheckbox, SendToMessenger, Group, Save) and unified login components into a singleLogincomponent.
Authentication & Social:
- Login- Modern unified login component with children as function pattern
- Like- Facebook like button
- Share- Share dialog component
- ShareButton- Direct share button
Content & Media:
- EmbeddedPost- Embed Facebook posts
- EmbeddedVideo- Embed Facebook videos
- Comments- Comments plugin
- CommentsCount- Comment count display
- Page- Facebook page plugin
Core:
- FacebookProvider- SDK initialization and context
- FacebookPixelProvider- Standalone pixel provider
- Parser - Parse XFBML tags
Removed in v10.0.1 (deprecated by Facebook):
- CustomChat- Customer chat (discontinued May 2024)
- MessageUs- Message button (deprecated Sept 2024)
- MessengerCheckbox- Opt-in checkbox (deprecating July 2025)
- SendToMessenger- Send to messenger (deprecated Sept 2024)
- Group- Facebook group plugin (deprecated)
- Save- Save button (deprecated)
- FacebookLogin&- LoginButton- Unified into- Logincomponent
Hooks:
- useLogin- Programmatic login control
- useProfile- Get user profile data
- useLoginStatus- Check authentication status
- useFacebook- Direct Facebook SDK access
- useLocale- Dynamic language switching
- usePixel- Facebook Pixel tracking
- usePageView- Automatic page view tracking
- useShare- Share functionality
The FacebookProvider component initializes the Facebook SDK and provides context to all child components.
<FacebookProvider 
  appId="YOUR_APP_ID"     // Required
  version="v23.0"         // Optional, defaults to latest
  language="en_US"        // Optional, defaults to en_US
  lazy={false}            // Optional, load SDK on demand
  debug={false}           // Optional, enable debug mode
  pixel={{                // Optional, Facebook Pixel configuration
    pixelId: "YOUR_PIXEL_ID",
    debug: false,
    autoConfig: true
  }}
>
  {/* Your app */}
</FacebookProvider>A modern, unified Facebook login component (replaces FacebookLogin and LoginButton):
// Basic usage with Tailwind CSS
<Login
  onSuccess={(response) => console.log('Success:', response)}
  onError={(error) => console.error('Error:', error)}
  className="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-lg"
>
  Continue with Facebook
</Login>
// With automatic profile fetching
<Login
  fields={['name', 'email', 'picture']}  // Specify which profile fields to fetch
  onSuccess={(response) => console.log('Login:', response)}
  onProfileSuccess={(profile) => {
    console.log('Profile:', profile);     // Receives the profile data automatically
  }}
  scope={['public_profile', 'email']}
  className="bg-gradient-to-r from-blue-600 to-blue-700 text-white px-6 py-3 rounded-lg"
>
  Sign in with Facebook
</Login>
// Children as function pattern for complete control
<Login
  onSuccess={(response) => console.log('Success:', response)}
  onError={(error) => console.error('Error:', error)}
  scope={['public_profile', 'email']}
>
  {({ onClick, isLoading, isDisabled }) => (
    <button
      onClick={onClick}
      disabled={isDisabled}
      className={`px-6 py-3 font-semibold rounded-lg transition-all ${
        isLoading 
          ? 'bg-gray-400 cursor-not-allowed' 
          : 'bg-blue-600 hover:bg-blue-700 text-white'
      }`}
    >
      {isLoading ? 'Connecting...' : 'Continue with Facebook'}
    </button>
  )}
</Login>
// Using custom component (as prop)
<Login 
  as="a" 
  href="#" 
  className="text-blue-600 hover:underline"
  onSuccess={(response) => console.log('Success:', response)}
>
  Connect Facebook Account
</Login>For programmatic login control:
function LoginComponent() {
  const { login, isLoading, error } = useLogin();
  
  async function handleLogin() {
    try {
      const response = await login({
        scope: 'email,user_friends',
        authType: ['rerequest'],
      });
      console.log('Logged in:', response);
    } catch (error) {
      console.error('Login failed:', error);
    }
  }
  return (
    <button onClick={handleLogin} disabled={isLoading}>
      Custom Login
    </button>
  );
}<Like 
  href="https://example.com" 
  colorScheme="dark" 
  showFaces 
  share 
/>// Using the share hook
function ShareExample() {
  const { share, isLoading } = useShare();
  
  return (
    <button onClick={() => share({ href: 'https://example.com' })}>
      Share
    </button>
  );
}
// Using the share button component
<ShareButton 
  href="https://example.com"
  className="my-share-button"
>
  Share this
</ShareButton><Comments 
  href="https://example.com/post" 
  numPosts={5}
  orderBy="reverse_time"
  width="100%"
/><Page 
  href="https://www.facebook.com/YourPage" 
  tabs="timeline,events,messages"
  width={500}
  height={600}
/>// Embedded Post
<EmbeddedPost 
  href="https://www.facebook.com/FacebookDevelopers/posts/10151471074398553" 
  width="500" 
/>
// Embedded Video
<EmbeddedVideo 
  href="https://www.facebook.com/facebook/videos/10153231379946729/" 
  width="500" 
  showText 
/>Change Facebook widget language dynamically:
import { useLocale } from 'react-facebook';
function LocaleSwitcher() {
  const { locale, setLocale, isChangingLocale, availableLocales } = useLocale();
  
  return (
    <select 
      value={locale} 
      onChange={(e) => setLocale(e.target.value)}
      disabled={isChangingLocale}
    >
      {availableLocales.map(loc => (
        <option key={loc} value={loc}>{loc}</option>
      ))}
    </select>
  );
}If you were using the old components, here are the migration paths:
// OLD: FacebookLogin or LoginButton
<FacebookLogin onSuccess={...} onFail={...} />
<LoginButton onSuccess={...} onError={...} />
// NEW: Login (unified component)
<Login onSuccess={...} onError={...} />
// Deprecated components (removed)
<CustomChat />     // ❌ Discontinued by Facebook (May 2024)
<MessageUs />      // ❌ Deprecated by Facebook (Sept 2024)
<Save />           // ❌ Deprecated by Facebook
<Group />          // ❌ Deprecated by FacebookGet started with Facebook Pixel tracking in just a few lines:
import { FacebookProvider, usePixel } from 'react-facebook';
// Option 1: With FacebookProvider (includes SDK + Pixel)
<FacebookProvider 
  appId="YOUR_APP_ID"
  pixel={{ pixelId: "YOUR_PIXEL_ID" }}
>
  <App />
</FacebookProvider>
// Option 2: Pixel only (no Facebook SDK)
<FacebookPixelProvider pixelId="YOUR_PIXEL_ID">
  <App />
</FacebookPixelProvider>
// Track events anywhere in your app
function TrackingComponent() {
  const { track, pageView, trackCustom } = usePixel();
  
  return (
    <div>
      <button onClick={() => track('Purchase', { value: 29.99, currency: 'USD' })}>
        Track Purchase
      </button>
      <button onClick={() => pageView()}>
        Track Page View
      </button>
      <button onClick={() => trackCustom('ButtonClick', { button: 'hero-cta' })}>
        Track Custom Event
      </button>
    </div>
  );
}Facebook Pixel can be configured directly in the FacebookProvider:
<FacebookProvider 
  appId="YOUR_APP_ID"
  pixel={{
    pixelId: "YOUR_PIXEL_ID",
    debug: true,
    autoConfig: true,
    advancedMatching: {
      // Add advanced matching parameters (hashed)
    }
  }}
>
  {/* Your app */}
</FacebookProvider>Access pixel functionality with a clean API:
import { usePixel } from 'react-facebook';
function PixelExample() {
  const { track, trackCustom, grantConsent, revokeConsent } = usePixel();
  
  const handlePurchase = () => {
    track('Purchase', {
      value: 29.99,
      currency: 'USD',
      content_name: 'Premium Plan',
      content_category: 'Subscription'
    });
  };
  const handleCustomEvent = () => {
    trackCustom('UserAction', {
      action_type: 'button_click',
      button_name: 'custom_action'
    });
  };
  return (
    <div>
      <button onClick={handlePurchase}>Track Purchase</button>
      <button onClick={handleCustomEvent}>Track Custom Event</button>
    </div>
  );
}Automatically track page views:
import { usePageView } from 'react-facebook';
function MyComponent() {
  // Track on mount
  usePageView({ trackOnMount: true });
  
  // Track on route changes
  usePageView({ trackOnRouteChange: true });
  
  return <div>My Component</div>;
}Facebook Pixel supports these standard events:
- PageView
- ViewContent
- Search
- AddToCart
- AddToWishlist
- InitiateCheckout
- AddPaymentInfo
- Purchase
- Lead
- CompleteRegistration
GDPR-compliant consent handling:
function ConsentManager() {
  const { grantConsent, revokeConsent } = usePixel();
  
  return (
    <div>
      <button onClick={grantConsent}>Accept Tracking</button>
      <button onClick={revokeConsent}>Decline Tracking</button>
    </div>
  );
}function ProfileDisplay() {
  const { profile, isLoading, error } = useProfile(['id', 'name', 'email']);
  
  if (isLoading) return <div>Loading profile...</div>;
  if (error) return <div>Error loading profile</div>;
  if (!profile) return <div>Not logged in</div>;
  
  return (
    <div>
      <img src={profile.picture.data.url} alt={profile.name} />
      <h2>{profile.name}</h2>
      <p>{profile.email}</p>
    </div>
  );
}function AuthStatus() {
  const { status, isLoading } = useLoginStatus();
  
  return (
    <div>
      Status: {isLoading ? 'Checking...' : status}
    </div>
  );
}Direct access to the Facebook SDK for advanced use cases:
import { useFacebook } from 'react-facebook';
function FacebookAPIExample() {
  const { api } = useFacebook();
  
  async function handleCustomAction() {
    if (!api) return;
    
    // Direct Graph API call
    const response = await api.api('/me/friends', 'GET');
    console.log(response);
    
    // Custom UI dialog
    await api.ui({
      method: 'share',
      href: 'https://example.com',
    });
  }
  
  return <button onClick={handleCustomAction}>Custom Action</button>;
}For advanced use cases, you can access the Facebook SDK directly:
import { useFacebook } from 'react-facebook';
function AdvancedComponent() {
  const { api } = useFacebook();
  
  async function makeCustomCall() {
    if (!api) return;
    
    const response = await api.api('/me/friends', 'GET');
    console.log(response);
  }
  
  return <button onClick={makeCustomCall}>Custom API Call</button>;
}Important: Like and Comments plugins are affected by Facebook's privacy changes in European regions:
What's affected:
- Like Button component
- Comments Plugin component
Requirements for EU/EEA users:
- Must be logged into Facebook
- Must have consented to "App and Website Cookies" in Facebook settings
Result: If these requirements aren't met, the components will not be visible to users.
Affected regions: All EU/EEA countries and the United Kingdom.
This is a Facebook platform limitation, not a library issue. Consider alternative engagement methods for European users.
This library doesn't include default styles. Use any CSS framework or styling solution:
// Tailwind CSS
<Login className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700" />
// CSS Modules  
<Login className={styles.facebookButton} />
// Styled Components
<Login className={styledButton} />Use only one FacebookProvider instance per application. If you need Facebook Pixel separately, you can use FacebookPixelProvider:
import { FacebookPixelProvider } from 'react-facebook';
<FacebookPixelProvider pixelId="YOUR_PIXEL_ID" debug={true}>
  {/* Components that need pixel access */}
</FacebookPixelProvider># Run component tests
npm run test:component
# Run with UI
npm run testAre you using react-facebook in production? We'd love to showcase your success story!
If you find this project useful, please consider becoming a sponsor.
Contributions are welcome! Please read our Contributing Guide.
MIT © Zlatko Fedor