react-use-intercom
repository·main·Indexed 18 days ago
https://github.com/devrnt/react-use-intercomA 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.
What's inside react-use-intercom
- The library is a React abstraction of IntercomJS. It aims to provide a one-on-one abstraction of the vanilla Intercom functionality using React hooks. It is compatible with existing Intercom instances loaded by other tools like Segment.
Pass custom attributes and authentication tokens to Intercom
mainWhen using
bootorupdate, 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 acustomAttributesobject using snake_case keys, as required by Intercom.Authentication Tokens: For secure data operations, pass an
authTokensobject containing your tokens (e.g.,security_tokenfor JWT). This is distinct fromintercomUserJwtused for identity verification.To refresh tokens during a session without a full
update, use thesetAuthTokensmethod fromuseIntercom.// 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' });Quickstart with IntercomProvider and useIntercom
mainTo use
react-use-intercom, wrap your application in theIntercomProviderwith your Intercom App ID. You can then use theuseIntercomhook in any child component to access Intercom methods likeboot,shutdown,hide,show, andupdate.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>; };View integration examples for different frameworks
mainThe repository provides several live examples demonstrating how to integrate
react-use-intercominto different React environments. You can explore these implementations on StackBlitz to see how theIntercomProvideranduseIntercomhook 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-routerUse react-use-intercom in a Vite app
mainThis example demonstrates how to integrate
react-use-intercominto a project using Vite. To run the example, you must provide your own Intercom application ID.- Navigate to the
vite-exampledirectory. - Replace the placeholder
INTERCOM_APP_IDin the environment configuration with your actual Intercom app ID.
INTERCOM_APP_ID=your_actual_app_id_here- Navigate to the
Use react-use-intercom in Gatsby
mainTo use
react-use-intercomwithin a Gatsby project, you must configure your Intercom application ID. Ensure you replace the placeholderINTERCOM_APP_IDwith your actual Intercom app ID in your environment configuration or Gatsby setup to enable the Intercom integration.INTERCOM_APP_ID=your_actual_app_id_hereInstall react-use-intercom
mainInstall the package using your preferred package manager:
# pnpm pnpm add react-use-intercom # npm npm install react-use-intercom # yarn yarn add react-use-intercompnpm add react-use-intercomTroubleshoot IntercomProvider and useIntercom errors
mainIf you encounter common errors while using
react-use-intercom, follow these steps:"Please wrap your component with IntercomProvider" error
- Ensure
IntercomProvideris initialized before callinguseIntercom(). - Initialize
IntercomProvideras high as possible in your application tree (e.g., inApp.tsxor_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 theIntercomPropsdocumentation. - Naming Convention: All props in
react-use-intercomusecamelCase. Do not usesnake_casefor standard props. - Exception: When using the
bootorupdatemethods from theuseIntercomhook, thecustomAttributesproperty still requiressnake_casekeys for the actual data sent to Intercom.
- Ensure
Use react-use-intercom in Next.js (Page Router)
mainThis example demonstrates how to integrate
react-use-intercominto 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_IDwith your actual Intercom app ID in your environment configuration or component props.Replace `INTERCOM_APP_ID` with your Intercom app id.Use react-use-intercom in Next.js (App Router)
mainThis example demonstrates how to integrate
react-use-intercomwithin a Next.js application using the App Router. To use this example as a template, ensure you replace the placeholderINTERCOM_APP_IDwith your actual Intercom application ID.INTERCOM_APP_ID=your_actual_app_id_hereDetect Messenger load success or failure
mainYou can monitor the status of the Intercom Messenger script loading using the
onLoadandonLoadFailedprops 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>Configure the IntercomProvider
mainThe
IntercomProviderinitializes thewindow.Intercominstance and ensures it is only initialized once. It also manages the attachment of event listeners. For maximum accessibility, place theIntercomProvideras high as possible in your application component tree. This allows any child component to access Intercom methods via theuseIntercomhook.Key Props:
appId(required): Your Intercom app ID.autoBoot: Iftrue, the provider automatically callsbootfor you.shouldInitialize: Controls if Intercom should be initialized (useful for multi-stage environments). Defaults totrue.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 thecrossOriginattribute 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> ); };