Skip to content

Instantly share code, notes, and snippets.

@dangerouse
Last active September 22, 2021 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dangerouse/6f889d966c64f027db0a8dff90c431b4 to your computer and use it in GitHub Desktop.
Save dangerouse/6f889d966c64f027db0a8dff90c431b4 to your computer and use it in GitHub Desktop.
CloudSponge Contact Picker in React 16.8+
// The ContactPicker component handles the stuff you don't want to think about
// when adding the CloudSponge Contact Picker to your React app or PWA.
// Usage:
// <ContactPicker cloudspongeKey="my-key-from-cloudsponge" options={{
// selectionLimit: 5,
// selectionLimitMessage: "That's too many contacts."
// }}>
// <button value="Add from Address Book" className="btn"></button>
// </ContactPicker>
// OR to launch the ContactPicker in response to an external setting/action:
// <ContactPicker open={isOpen} cloudspongeKey="localhost-only" options={{}}/>
// OR to create a deep link directly on one of the sources:
// <ContactPicker source="gmail" cloudspongeKey="localhost-only" options={{}}>
// <button className="btn" value="Pick from your Google Contacts"></button>
// </ContactPicker>
import React from 'react';
import useScript from 'react-script-hook';
export default function ContactPicker({
cloudspongeKey,
options = {},
source = null,
open = false,
children = null,
}) {
const [loading, error] = useScript({src: `https://api.cloudsponge.com/widget/${cloudspongeKey}.js`});
React.useEffect(() => {
if (loading) return;
if (error) return;
if (!window.cloudsponge) return;
// normal initialization here
if (!open) return cloudsponge.init(options);
// if open is true, then we'll need to wait for the
// cloudsponge object to finish applying the options
// before launching the Contact Picker UI.
cloudsponge.init({
...options,
afterInit: () => {
options.afterInit && options.afterInit();
launch();
}
});
}, [loading, error, options, open]);
const launch = () => {
if (window.cloudsponge) {
cloudsponge.launch(source);
}
}
return (
<span onClick={launch}>
{children}
</span>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment