Integrating Facebook Customer Chat into a React.js App

Konstantin Tarkus
Level Up Coding
Published in
2 min readMar 18, 2019

--

With Facebook Customer Chat widget you’re now able to connect with your website visitors (customers) even after they left your site. How cool is that ;)

View source code at https://github.com/kriasoft/react-firebase-starter

You start by creating a Facebook Page for your app or product. Find your Page ID in the About section — you will need that for the widget. Then go to Page Settings > Messenger Platform and whitelist your domain name, otherwise, the widget won’t show up on your site after integrating it.

The widget itself can be integrated by injecting Customer Chat SDK script into your React.js app, which contains the Facebook JavaScript SDK and a few more things to make the chat work.

https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js

Will it negatively affect the initial page load time?

Yes, a little, but nothing stops us from loading this SDK lazily after the app was fully rendered in the browser.

For this to work, you would create a wrapper function that would allow loading Customer Chat SDK on demand as well as queuing all the API calls your app may make until the SDK is fully loaded and initialized.

The script relies on a global window.config variable containing your Facebook App ID (that was hydrated and injected into the HTML page during server-side rendering, but that’s another topic).

Now instead of calling Facebook SDK API directly, you would use this wrapper function (for the lack of a better name I called it fb in this example):

// BEFORE
FB.CustomerChat.show(true);
// AFTER
fb(FB => FB.CustomerChat.show(true));

Note that, you cannot call API methods until the SDK was fully initialized, so this wrapper function would save us from using SDK prematurely.

Customer Chat React Component

Now, let’s create the Customer Chat React Component itself, it would look something like this:

You would just place it into your top-level React component (e.g. Layout) and it would do the trick.

function Layout({ classes: s, children }) {
return (
<div className={s.root}>
<Toolbar />
<main className={s.content}>{children}</main>
<CutomerChat />
</div>
);
}

In a future article, I will share with you a couple of code recipes for creating chatbots. Stay tuned! Check out the demo and complete example in the React Starter Kit project on GitHub. Try it out! And, I will chat with you on the other end :)

--

--

Empowering startups with cutting-edge expertise: software architecture, optimal practices, database design, web infrastructure, and DevOps mastery.