Using UI Elements within a React application

All the UI Elements can be used within an existing React application. To aid mounting and to ensure correct updating when props change, we recommend creating a “wrapper” component to handle the rendering of the UI Element.

Installation #

If you prefer, you can install the UI Elements with npm.

npm install --save cronofy-elements

After installing, you will need to import the Elements into your JavaScript:

import * as CronofyElements from "cronofy-elements";

Wrapper Components #

When using the UI Elements within a React project, we recommend creating a wrapper component to handle the mounting of the UI Element. This allows the UI Element to be stored in internal state, which in turn means that the UI Element can be automatically updated and re-rendered whenever the provided options prop changes.

A simple mounting component #

Because the UI Elements require a DOM node to mount on, we recommend initializing the UI Element in a useEffect hook. This allows the mounting point to be rendered before the UI Element is initalized (without a suitable mounting point, the UI Element would not appear on the page).

const AvailabilityViewerWrapper = ({ options }) => {
    const [element, setElement] = useState(null);

    useEffect(() => {
        if (!element) {
            setElement(
                CronofyElements.AvailabilityViewer(options)
            );
        }
    }, []);

    return <div id="cronofy-availability-viewer" />;
};

The AvailabilityViewerWrapper component can then be used just like any normal React component:

import AvailabilityViewerWrapper from "./AvailabilityViewerWrapper";

const YourReactApp = () => {
    const availabilityOptions = {
        // Your options for the Availability Viewer
    };

    return (
        <div>
            {/* Other application code */}
            <AvailabilityViewerWrapper options={availabilityOptions} />
        </div>
    );
};

Re-rendering when options are changed #

By adding a useEffect hook tied to the options prop, we can ensure that the UI Element fires it’s update() method whenever the options prop changes.

useEffect(() => {
    if (element) {
        element.update(options);
    }
}, [options]);

Example code #

Here is an example of a full wrapper component for the AvailabilityViewer UI Element.

import React, { useEffect, useState } from "react";
import * as CronofyElements from "cronofy-elements";

const AvailabilityViewerWrapper = ({ options }) => {
    const [element, setElement] = useState(null);

    useEffect(() => {
        if (!element) {
            setElement(
                CronofyElements.AvailabilityViewer(options)
            );
        }
    }, []);

    useEffect(() => {
        if (element) {
            element.update(options);
        }
    }, [options]);

    return <div id="cronofy-availability-viewer" />;
};

export default AvailabilityViewerWrapper;