Cristian Vasta

Cristian Vasta

1607006520

A React Intercom Integration Powered by Hooks

react-use-intercom

A React Intercom integration powered by hooks.

Features

  • Hooks
  • Written in TypeScript
  • Documented, self explaining methods
  • Tiny size without any external libraries
  • Safeguard for SSR environments

Installation

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

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 useIntercom() anywhere.

Props
name type description required default
appId string app ID of your Intercom instance true
children React.ReactNode React children true
autoBoot boolean indicates if Intercom should be automatically booted. If true no need to call boot, the IntercomProvider will call it for you false false
onHide () => void triggered when the Messenger hides false
onShow () => void triggered when the Messenger shows false
onUnreadCountChange (number) => void triggered when the current number of unread messages changes false
shouldInitialize boolean indicates if the Intercom should be initialized. Can be used in multistaged environment false true
apiBase string If 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
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);
  };

  return (
    <IntercomProvider
      appId={INTERCOM_APP_ID}
      onHide={onHide}
      onShow={onShow}
      onUnreadCountChange={onUnreadCountChange}
      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.

Methods
name type description
boot (props?: IntercomProps) => void boots the Intercom instance, not needed if autoBoot in IntercomProvider is true
shutdown () => void shuts down the Intercom instance
hardShutdown () => void same functionality as shutdown, but makes sure the Intercom cookies, window.Intercom and window.intercomSettings are removed.
update (props?: IntercomProps) => void updates the Intercom instance with the supplied props. To initiate a ‘ping’, call update without props
hide () => void hides the Messenger, will call onHide if supplied to IntercomProvider
show () => void shows the Messenger, will call onShow if supplied to IntercomProvider
showMessages () => void shows the Messenger with the message list
showNewMessages (content?: string) => void shows the Messenger as if a new conversation was just created. If content is passed, it will fill in the message composer
getVisitorId () => string gets the visitor id
startTour (tourId: number) => void starts a tour based on the tourId
trackEvent (event: string, metaData?: object) => void submits an event with optional metaData
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,
    showNewMessages,
    getVisitorId,
    startTour,
    trackEvent,
  } = useIntercom();

  const bootWithProps = () => boot({ name: 'Russo' });
  const updateWithProps = () => update({ name: 'Ossur' });
  const handleNewMessages = () => showNewMessages();
  const handleNewMessagesWithContent = () => showNewMessages('content');
  const handleGetVisitorId = () => console.log(getVisitorId());
  const handleStartTour = () => startTour(123);
  const handleTrackEvent = () => trackEvent('invited-friend');
  const handleTrackEventWithMetaData = () =>
    trackEvent('invited-frind', {
      name: 'Russo',
    });

  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={handleTrackEvent}>Track event</button>
      <button onClick={handleTrackEventWithMetaData}>
        Track event with metadata
      </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 are these 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

Example 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

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

To reduce the amount of re-renders in your React application I suggest to make use of useCallback

TLDR: useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

This can be applied to both the IntercomProvider events and the useIntercom methods. It depends on how many times your main app gets re-rendered.

Example

import * as React from 'react';

import { IntercomProvider, useIntercom } from 'react-use-intercom';

const INTERCOM_APP_ID = 'your-intercom-app-id';

const App = () => {
  // const onHide = () => console.log('Intercom did hide the Messenger');
  const onHide = React.useCallback(
    () => console.log('Intercom did hide the Messenger'),
    [],
  );

  return (
    <IntercomProvider appId={INTERCOM_APP_ID} onHide={onHide}>
      <HomePage />
    </IntercomProvider>
  );
};

const HomePage = () => {
  const { boot } = useIntercom();

  // const bootWithProps = () => boot({ name: 'Russo' });
  const bootWithProps = React.useCallback(() => boot({ name: 'Russo' }), [boot]);

  return <button onClick={bootWithProps}>Boot with props</button>;
};

Download Details:

Author: devrnt

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

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

#react #reactjs #javascript

What is GEEK

Buddha Community

A React Intercom Integration Powered by Hooks
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

The Ugly Side of React Hooks

In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.

Let’s break down the motivation for ditching classes in favor of hooks, as described in the official React’s docs.

Motivation #1: Classes are confusing

we’ve found that classes can be a large barrier to learning React. You have to understand how "this"_ works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable syntax proposals, the code is very verbose […] The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers._

Ok, I can agree that

thiscould be a bit confusing when you are just starting your way in Javascript, but arrow functions solve the confusion, and calling a_stage 3_feature that is already being supported out of the box by Typescript, an “unstable syntax proposal”, is just pure demagoguery. React team is referring to theclass fieldsyntax, a syntax that is already being vastly used and will probably soon be officially supported

class Foo extends React.Component {
  onPress = () => {
    console.log(this.props.someProp);
  }

  render() {
    return <Button onPress={this.onPress} />
  }
}

As you can see, by using a class field arrow function, you don’t need to bind anything in the constructor, and

this will always point to the correct context.

And if classes are confusing, what can we say about the new hooked functions? A hooked function is not a regular function, because it has state, it has a weird looking

this(aka_useRef_), and it can have multiple instances. But it is definitely not a class, it is something in between, and from now on I will refer to it as aFunclass. So, are those Funclasses going to be easier for human and machines? I am not sure about machines, but I really don’t think that Funclasses are conceptually easier to understand than classes. Classes are a well known and thought out concept, and every developer is familiar with the concept ofthis, even if in javascript it’s a bit different. Funclasses on the other hand, are a new concept, and a pretty weird one. They feel much more magical, and they rely too much on conventions instead of a strict syntax. You have to follow somestrict and weird rules, you need to be careful of where you put your code, and there are many pitfalls. Telling me to avoid putting a hook inside anifstatement, because the internal mechanism of hooks is based on call order, is just insane! I would expect something like this from a half baked POC library, not from a well known library like React. Be also prepared for some awful naming like useRef (a fancy name forthis),useEffect ,useMemo,useImperativeHandle(say whatt??) and more.

The syntax of classes was specifically invented in order to deal with the concept of multiple instances and the concept of an instance scope (the exact purpose of

this ). Funclasses are just a weird way of achieving the same goal, using the wrong puzzle pieces. Many people are confusing Funclasses with functional programming, but Funclasses are actually just classes in disguise. A class is a concept, not a syntax.

Oh, and about the last note:

The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers

Until now, the distinction was pretty clear- if you needed a state or lifecycle methods, you used a class, otherwise it doesn’t really matter if you used a function or class. Personally, I liked the idea that when I stumbled upon a function component, I could immediately know that this is a “dumb component” without a state. Sadly, with the introduction of Funclasses, this is not the situation anymore.

#react #react-hooks #javascript #reactjs #react-native #react-hook #rethinking-programming #hackernoon-top-story

Juana  O'Keefe

Juana O'Keefe

1603127640

Hooks, Hooks, Hooks!

Prior to 2018, React, an already powerful and widely-used javascript library for building user interfaces, had 3 cumbersome issues:

  1. Reusing logic: in order to to create dynamic interfaces where state is manipulated, logic was constantly being copied for seemingly simple tasks like updating the state from a form field. This often would lead to complicated and bloated data structures.
  2. Giant components: logic often times gets split amongst various lifecycle. methods in order to keep your application working.
  3. Confusing classes: invariably with reused logic and oversized components, our classes themselves can become confusing for both user and the machine.

As Dan Abramov of the React Dev team describes it, these are really three separate issues, but rather systems of the same problem: before 2018, _React did not provide a stateful primitive that is simpler than incorporating a class component and its associated logic. _At one point, React used mixins to pseudo-resolve this issue, but that ultimately created more problems that it solved.

How did the React team resolve this seemingly singular, but hugely impactful inconvenience? Hooks to the rescue.

Image for post

#software-engineering #react-conf-2018 #hooks #react #react-conference #react native