react-use-intercom

repository·main·Indexed 18 days ago

https://github.com/devrnt/react-use-intercom

A lightweight, type-safe, and SSR-friendly React integration for Intercom powered by hooks. It provides a React abstraction of IntercomJS via the IntercomProvider and useIntercom hook, allowing developers to control Intercom functionality such as boot, shutdown, show, hide, and trackEvent. It includes built-in support and examples for Next.js (App and Page Routers), Gatsby, and Vite.

Tokens
6.6K
Snippets
22
Records
26
Agent score
62%

What's inside react-use-intercom

  1. Pass custom attributes and authentication tokens to Intercom

    main

    When using boot or update, you can pass user attributes and authentication tokens.

    Custom Attributes: While standard Intercom attributes are camel cased in react-use-intercom, any custom attributes must be passed inside a customAttributes object using snake_case keys, as required by Intercom.

    Authentication Tokens: For secure data operations, pass an authTokens object containing your tokens (e.g., security_token for JWT). This is distinct from intercomUserJwt used for identity verification.

    To refresh tokens during a session without a full update, use the setAuthTokens method from useIntercom.

    // Passing custom attributes and auth tokens during boot
    const { boot } = useIntercom();
    
    boot({
      name: 'Russo',
      customAttributes: { custom_attribute_key: 'hi there' },
      authTokens: {
        security_token: 'abc...', // JWT token
        api_token: 'xyz...',
      }
    });
    
    // Refreshing tokens without a full update
    const { setAuthTokens } = useIntercom();
    setAuthTokens({ security_token: 'refreshed-jwt' });
  2. Quickstart with IntercomProvider and useIntercom

    main

    To use react-use-intercom, wrap your application in the IntercomProvider with your Intercom App ID. You can then use the useIntercom hook in any child component to access Intercom methods like boot, shutdown, hide, show, and update.

    The library includes safeguards for SSR environments like NextJS and Gatsby.

    import * as React from 'react';
    import { IntercomProvider, useIntercom } from 'react-use-intercom';
    
    const INTERCOM_APP_ID = 'your-intercom-app-id';
    
    const App = () => (
      <IntercomProvider appId={INTERCOM_APP_ID}>
        <HomePage />
      </IntercomProvider>
    );
    
    // Anywhere in your app
    const HomePage = () => {
      const { boot, shutdown, hide, show, update } = useIntercom();
    
      return <button onClick={boot}>Boot intercom! ☎️</button>;
    };
  3. View integration examples for different frameworks

    main

    The repository provides several live examples demonstrating how to integrate react-use-intercom into different React environments. You can explore these implementations on StackBlitz to see how the IntercomProvider and useIntercom hook are configured for specific frameworks:

    • Gatsby: Integration within the Gatsby framework.
    • Next.js (Page Router): Integration using the traditional Next.js Page Router.
    • Next.js (App Router): Integration using the modern Next.js App Router architecture.
    https://stackblitz.com/github/devrnt/react-use-intercom/tree/main/apps/examples/gatsby
    https://stackblitz.com/github/devrnt/react-use-intercom/tree/main/apps/examples/nextjs-page-router
    https://stackblitz.com/github/devrnt/react-use-intercom/tree/main/apps/examples/nextjs-app-router
  4. Use react-use-intercom in a Vite app

    main

    This example demonstrates how to integrate react-use-intercom into a project using Vite. To run the example, you must provide your own Intercom application ID.

    1. Navigate to the vite-example directory.
    2. Replace the placeholder INTERCOM_APP_ID in the environment configuration with your actual Intercom app ID.
    INTERCOM_APP_ID=your_actual_app_id_here
  5. Use react-use-intercom in Gatsby

    main

    To use react-use-intercom within a Gatsby project, you must configure your Intercom application ID. Ensure you replace the placeholder INTERCOM_APP_ID with your actual Intercom app ID in your environment configuration or Gatsby setup to enable the Intercom integration.

    INTERCOM_APP_ID=your_actual_app_id_here
  6. Troubleshoot IntercomProvider and useIntercom errors

    main

    If you encounter common errors while using react-use-intercom, follow these steps:

    "Please wrap your component with IntercomProvider" error

    • Ensure IntercomProvider is initialized before calling useIntercom().
    • Initialize IntercomProvider as high as possible in your application tree (e.g., in App.tsx or _app.tsx).
    • Crucial: Do not call useIntercom() in the same component where you have defined the <IntercomProvider>. The hook must be used in a child component of the provider.

    "Some invalid props were passed to IntercomProvider" error

    • Verify that all properties passed to <IntercomProvider> are correct by checking the IntercomProps documentation.
    • Naming Convention: All props in react-use-intercom use camelCase. Do not use snake_case for standard props.
    • Exception: When using the boot or update methods from the useIntercom hook, the customAttributes property still requires snake_case keys for the actual data sent to Intercom.
  7. Use react-use-intercom in Next.js (Page Router)

    main

    This example demonstrates how to integrate react-use-intercom into a Next.js application using the Pages Router. To use this setup, you must provide your specific Intercom application ID.

    Ensure you replace the placeholder INTERCOM_APP_ID with your actual Intercom app ID in your environment configuration or component props.

    Replace `INTERCOM_APP_ID` with your Intercom app id.
  8. Detect Messenger load success or failure

    main

    You can monitor the status of the Intercom Messenger script loading using the onLoad and onLoadFailed props on <IntercomProvider />. This is useful for showing loading states or offering alternative support channels if the script is blocked by firewalls or extensions.

    To get full error details for errors thrown by the Messenger loader script, pass the crossOrigin="anonymous" prop to <IntercomProvider /> (this utilizes standard HTML <script> attribute behavior).

    <IntercomProvider
      appId={INTERCOM_APP_ID}
      onLoad={() => console.log('Messenger loaded')}
      onLoadFailed={() => console.log('Messenger failed to load')}
      crossOrigin="anonymous"
    >
      {/* Your App */}
    </IntercomProvider>
  9. Configure the IntercomProvider

    main

    The IntercomProvider initializes the window.Intercom instance and ensures it is only initialized once. It also manages the attachment of event listeners. For maximum accessibility, place the IntercomProvider as high as possible in your application component tree. This allows any child component to access Intercom methods via the useIntercom hook.

    Key Props:

    • appId (required): Your Intercom app ID.
    • autoBoot: If true, the provider automatically calls boot for you.
    • shouldInitialize: Controls if Intercom should be initialized (useful for multi-stage environments). Defaults to true.
    • onHide, onShow, onUnreadCountChange, onUserEmailSupplied, onLoad, onLoadFailed: Event listeners for various Intercom lifecycle events.
    • apiBase: Custom endpoint for Messenger requests (format: https://${INTERCOM_APP_ID}.intercom-messenger.com).
    • crossOrigin: Sets the crossOrigin attribute on the Messenger <script> (e.g., 'anonymous' for full error details).
    const App = () => {
      const [unreadMessagesCount, setUnreadMessagesCount] = React.useState(0);
    
      const onHide = () => console.log('Intercom did hide the Messenger');
      const onShow = () => console.log('Intercom did show the Messenger');
      const onUnreadCountChange = (amount: number) => {
        console.log('Intercom has a new unread message');
        setUnreadMessagesCount(amount);
      };
      const onUserEmailSupplied = () => {
        console.log('Visitor has entered email');
      };
    
      return (
        <IntercomProvider
          appId={INTERCOM_APP_ID}
          onHide={onHide}
          onShow={onShow}
          onUnreadCountChange={onUnreadCountChange}
          onUserEmailSupplied={onUserEmailSupplied}
          autoBoot
        >
          <p>Hi there, I am a child of the IntercomProvider</p>
        </IntercomProvider>
      );
    };