5.4.0 • Published 9 days ago

react-use-intercom v5.4.0

Weekly downloads
13,015
License
MIT
Repository
github
Last release
9 days ago

Features

  • Hooks
  • Written in TypeScript
  • Documented, self explaining methods
  • Tiny size without any external libraries
  • Safeguard for SSR environments (NextJS, Gatsby)
  • Compatible to hook into existing Intercom instance (loaded by Segment)

Installation

# pnpm
pnpm add react-use-intercom

# npm
npm install react-use-intercom

# yarn
yarn add react-use-intercom

Quickstart

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>;
};

Context

This library is a React abstraction of IntercomJS. react-use-intercom tries to keep as close as a one-on-one abstraction of the "vanilla" Intercom functionality.

Note that a lot of issues could be related to the vanilla IntercomJS. Please see https://forum.intercom.com/s/ before reporting an issue here.

Links

API

IntercomProvider

IntercomProvider is used to initialize the window.Intercom instance. It makes sure the initialization is only done once. If any listeners are passed, the IntercomProvider will make sure these are attached.

Place the IntercomProvider as high as possible in your application. This will make sure you can call useIntercom anywhere.

Props

nametypedescriptionrequireddefault
appIdstringapp ID of your Intercom instancetrue
childrenReact.ReactNodeReact childrentrue
autoBootbooleanindicates if Intercom should be automatically booted. If true no need to call boot, the IntercomProvider will call it for youfalsefalse
onHide() => voidtriggered when the Messenger hidesfalse
onShow() => voidtriggered when the Messenger showsfalse
onUnreadCountChange(number) => voidtriggered when the current number of unread messages changesfalse
onUserEmailSupplied() => voidtriggered when a visitor enters their email into the Messengerfalse
shouldInitializebooleanindicates if the Intercom should be initialized. Can be used in multistaged environmentfalsetrue
apiBasestringIf you need to route your Messenger requests through a different endpoint than the default. Generally speaking, this is not needed. Format: https://${INTERCOM_APP_ID}.intercom-messenger.com (See: https://github.com/devrnt/react-use-intercom/pull/96)false
initializeDelaynumberIndicates if the intercom initialization should be delayed, delay is in ms, defaults to 0. See https://github.com/devrnt/react-use-intercom/pull/236false
autoBootPropsIntercomPropsPass properties to boot method when autoBoot is truefalse

Example

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>
  );
};

useIntercom

Used to retrieve all methods bundled with Intercom. These are based on the official Intercom docs. Some extra methods were added to improve convenience.

Make sure IntercomProvider is wrapped around your component when calling useIntercom().

Remark - You can't use useIntercom() in the same component where IntercomProvider is initialized.

API

nametypedescription
isOpenbooleanthe visibility status of the messenger
boot(props?: IntercomProps) => voidboots the Intercom instance, not needed if autoBoot in IntercomProvider is true
shutdown() => voidshuts down the Intercom instance
hardShutdown() => voidsame functionality as shutdown, but makes sure the Intercom cookies, window.Intercom and window.intercomSettings are removed.
update(props?: IntercomProps) => voidupdates the Intercom instance with the supplied props. To initiate a 'ping', call update without props
hide() => voidhides the Messenger, will call onHide if supplied to IntercomProvider
show() => voidshows the Messenger, will call onShow if supplied to IntercomProvider
showMessages() => voidshows the Messenger with the message list
showNewMessage(content?: string) => voidshows the Messenger as if a new conversation was just created. If content is passed, it will fill in the message composer
getVisitorId() => stringgets the visitor id
startTour(tourId: number) => voidstarts a tour based on the tourId
startChecklist(checklistId: number) => voidstarts a checklist based on the checklistId
trackEvent(event: string, metaData?: object) => voidsubmits an event with optional metaData
showArticle(articleId: string) => voidopens the Messenger with the specified article by articleId
startSurvey(surveyId: number) => voidTrigger a survey in the Messenger by surveyId
showSpace(spaceName: IntercomSpace) => voidOpens the Messenger with the specified space
showTicket(ticketId: number) => voidOpens the Messenger with the specified ticket by ticketId
showConversation(conversationId: number) => voidOpens the Messenger with the specified conversation by conversationId

Example

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>
);

const HomePage = () => {
  const {
    boot,
    shutdown,
    hardShutdown,
    update,
    hide,
    show,
    showMessages,
    showNewMessage,
    getVisitorId,
    startTour,
    startChecklist,
    trackEvent,
    showArticle,
    startSurvey,
    showSpace,
    showTicket,
    showConversation
  } = useIntercom();

  const bootWithProps = () => boot({ name: 'Russo' });
  const updateWithProps = () => update({ name: 'Ossur' });
  const handleNewMessages = () => showNewMessage();
  const handleNewMessagesWithContent = () => showNewMessage('content');
  const handleGetVisitorId = () => console.log(getVisitorId());
  const handleStartTour = () => startTour(123);
  const handleStartChecklist = () => startChecklist(456);
  const handleTrackEvent = () => trackEvent('invited-friend');
  const handleTrackEventWithMetaData = () =>
    trackEvent('invited-frind', {
      name: 'Russo',
    });
  const handleShowArticle = () => showArticle(123456);
  const handleStartSurvey = () => startSurvey(123456);
  const handleShowSpace = () => showSpace('tasks');
  const handleShowTicket = () => showTicket(123);
  const handleShowConversation = () => showConversation(123);

  return (
    <>
      <button onClick={boot}>Boot intercom</button>
      <button onClick={bootWithProps}>Boot with props</button>
      <button onClick={shutdown}>Shutdown</button>
      <button onClick={hardShutdown}>Hard shutdown</button>
      <button onClick={update}>Update clean session</button>
      <button onClick={updateWithProps}>Update session with props</button>
      <button onClick={show}>Show messages</button>
      <button onClick={hide}>Hide messages</button>
      <button onClick={showMessages}>Show message list</button>
      <button onClick={handleNewMessages}>Show new messages</button>
      <button onClick={handleNewMessagesWithContent}>
        Show new message with pre-filled content
      </button>
      <button onClick={handleGetVisitorId}>Get visitor id</button>
      <button onClick={handleStartTour}>Start tour</button>
      <button onClick={handleStartChecklist}>Start checklist</button>
      <button onClick={handleTrackEvent}>Track event</button>
      <button onClick={handleTrackEventWithMetaData}>
        Track event with metadata
      </button>
      <button onClick={handleShowArticle}>Open article in Messenger</button>
      <button onClick={handleStartSurvey}>Start survey in Messenger</button>
      <button onClick={handleShowSpace}>Open space in Messenger</button>
      <button onClick={handleShowTicket}>Open ticket in Messenger</button>
      <button onClick={handleShowConversation}>Open conversation in Messenger</button>
    </>
  );
};

IntercomProps

All the Intercom default attributes/props are camel cased (appId instead of app_id) in react-use-intercom, see IntercomProps to see what attributes you can pass to boot or update. Or check the Intercom docs to see all the available attributes/props.

Remark - all the listed Intercom attributes here are snake cased, in react-use-intercom these are camel cased.

Custom attributes

Still want to pass custom attributes to Intercom? Whether boot or update is used, you can add your custom properties by passing these through customAttributes in the boot or update method.

Remark - the keys of the customAttributes object should be snake cased (this is how Intercom wants them). They are rawly passed to Intercom.

const { boot } = useIntercom();

boot({ 
 name: 'Russo',
 customAttributes: { custom_attribute_key: 'hi there' },
})

Playground

Small playground to showcase the functionalities of react-use-intercom.

useIntercom

https://devrnt.github.io/react-use-intercom/#/useIntercom

useIntercom (with Intercom tour)

https://devrnt.github.io/react-use-intercom/#/useIntercomTour

Examples

Go to examples to check out some integrations (Gatsby, NextJS...).

TypeScript

All the possible pre-defined options to pass to the Intercom instance are typed. So whenever you have to pass IntercomProps, all the possible properties will be available out of the box. These props are JavaScript 'friendly', so camelCase. No need to pass the props with snake_cased keys.

Remark - if you want to pass custom properties, you should still use snake_cased keys.

Troubleshoot

  • I'm seeing Please wrap your component with IntercomProvider in the console.

    Make sure IntercomProvider is initialized before calling useIntercom(). You only need to initialize IntercomProvider once. It is advised to initialize IntercomProvider as high as possible in your application tree.

Make sure you aren't calling useIntercom() in the same component where you initialized IntercomProvider.

  • I'm seeing Some invalid props were passed to IntercomProvider. Please check following props: [properties] in the console.

    Make sure you're passing the correct properties to the IntercomProvider. Check IntercomProvider to see all the properties. Mind that all the properties in react-use-intercom are camel cased, except for the customAttributes property in the boot and update method from useIntercom.

Advanced

Delay initialization

<IntercomProvider /> uses an official intercom snippet and is directly initialized on load. In the background this snippet will load some external code that makes Intercom work. All of this magic happens on the initial load and in some use cases this can become problematic (E.g. when LCP is priority).

Since v1.2.0 it's possible to delay this initialisation by passing initializeDelay in <IntercomProvider /> (it's in milliseconds). However most of the users won't need to mess with this.

For reference see https://github.com/devrnt/react-use-intercom/pull/236 and https://forum.intercom.com/s/question/0D52G00004WxWLs/can-i-delay-loading-intercom-on-my-site-to-reduce-the-js-load

5.4.0

9 days ago

5.3.0

4 months ago

5.2.0

4 months ago

5.1.4

11 months ago

5.1.3

11 months ago

5.1.2

11 months ago

5.1.1

11 months ago

5.1.0

12 months ago

5.0.0

1 year ago

2.1.0

1 year ago

3.0.3

1 year ago

3.0.2

1 year ago

3.0.1

1 year ago

3.0.0

1 year ago

4.1.0

1 year ago

4.0.0

1 year ago

1.5.2

2 years ago

2.0.0

2 years ago

1.5.1

2 years ago

1.5.0

2 years ago

1.4.1

2 years ago

1.4.0

3 years ago

1.3.0

3 years ago

1.2.0

3 years ago

1.1.9

3 years ago

1.1.8

3 years ago

1.1.7

3 years ago

1.1.6

3 years ago

1.1.5

3 years ago

1.1.4

3 years ago

1.1.3

3 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago

0.4.0

4 years ago

0.3.1

4 years ago

0.3.0

4 years ago

0.2.0

4 years ago

0.1.2

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago