SPFx – Using UniteGallery jQuery plugin

Introduction

In this post, let us see how we can use the UniteGallery jQuery plugin which is the responsive slider and carousel plugin in SharePoint Framework Webpart.

Let us start by creating a new web part project using yeoman SharePoint generator, before that create a folder where you want to create the web part. Navigate to that folder and run the below command

yo @microsoft/sharepoint

The generator will asks you couple of questions,

  • Enter the webpart name as your solution name, and then select Enter.
  • Select Create a subfolder with solution name for where to place the files.
  • Select Y to allow the solution to be deployed to all sites immediately.
  • Select N on the question if solution contains unique permissions.
  • Enter the webpart name
  • Enter the webpart description
  • Choose the framework as ‘React

Open the code in VSCode which is my favorite and flexible code editor for SharePoint Framework. You can directly open the project folder from the file menu or use the below command to open the VSCode from command line.

cd \web part folder\
code .

Before starting to use the plugin, there are couple of things you have to do.

  1. Create a folder named js under src folder.
  2. Download the below mentioned files from cdn and then paste it to the js folder.
    1. unitegallery.min.js
    2. ug-theme-slider.js
    3. ug-theme-carousel.js

Once done with the above, navigate to the config.json file and copy-paste the below json inside the externals section.

        "jquery": {
            "path": "https://code.jquery.com/jquery-3.1.0.min.js",
            "globalName": "jQuery"
        },
        "unitegallery": {
            "path": "./src/js/ug-unitegallery.min.js",
            "globalName": "jQuery",
            "globalDependencies": [
                "jquery"
            ]
        },
        "ug-theme-slider": {
            "path": "./src/js/ug-theme-slider.js",
            "globalName": "jQuery",
            "globalDependencies": [
                "jquery",
                "unitegallery"
            ]
        },
        "ug-theme-carousel": {
            "path": "./src/js/ug-theme-carousel.js",
            "globalName": "jQuery",
            "globalDependencies": [
                "jquery",
                "unitegallery"
            ]
        }

The last step before coding is to install the jQuery types. Execute the below command.

npm install @types/jquery

Navigate to the <webpart>.tsx file and copy-paste the below code. Replace the imports with the below code.

import * as React from 'react';
import styles from './UniteGallerySample.module.scss';
import { SPComponentLoader } from '@microsoft/sp-loader';
import * as $ from 'jquery';
require('unitegallery');
require('ug-theme-slider');

Declare a state interface to hold the GUID of the div which is dynamic. This is to make the web part as reusable within a single page.

export interface IUniteGallerySampleState {
    divGuid: string;
}

I had used the static images to show the slider or carousel using unitegallery plugin, the same can be fetched from a list or library based on the requirement.

const images: any[] = [
    'https://image.freepik.com/free-vector/bridge-with-full-moon-scenery-landscape_105940-72.jpg',
    'https://image.freepik.com/free-vector/three-geometric-neon-frames-banner-with-text-space_1017-25564.jpg',
    'https://image.freepik.com/free-vector/illustration-space_29937-1093.jpg'
];

Below will be actual code under the class. You can copy-paste the below code in the given order for better understanding. Declared a constructor and assigned the state value and also loaded the css for the plugin using SPComponentLoader.

constructor(props: IUniteGallerySampleProps) {
        super(props);
        this.state = {
            divGuid: ''
        };

SPComponentLoader.loadCss('https://cdnjs.cloudflare.com/ajax/libs/unitegallery/1.7.40/css/unite-gallery.min.css');
    }

Declared a function to generate the guid for the div that holds the images.

public s4 = () => {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    };

    public getGuid = () => {
        return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + this.s4() + this.s4();
    };

Declared a function to get the images from the const and then returned as an JSX Element.

public _getImages = (): JSX.Element => {
        return (
            <>
                {images.map((img: any) => {
                    return (
                        <img alt={"Sample"} src={img} data-image={img} />
                    );
                })}
            </>
        );
    }

Declared a function to call the jQuery plugin to initiate the slider or carousel.

public _loadUniteGallery = () => {
        ($ as any)(`#${this.state.divGuid}_divGallery`).unitegallery({});
    }

Declared a componentDidMount method to set the guid to the state variable and then to call the method to initiate the jQuery plugin.

public componentDidMount = () => {
        let divGuid: string = this.getGuid();
        this.setState({ divGuid }, () => {
            this._loadUniteGallery();
        });
    }

Under the render method, design the component. The design is very simple. We had declared a parent div and its ID has been set to the generated guid from the state value and then the static text, inside the div we call the method to load the images.

public render(): React.ReactElement<IUniteGallerySampleProps> {
        const { divGuid } = this.state;
        return (
            <>
                {divGuid &&
                    <div id={`${divGuid}_divGallery`} style={{ display: '' }}>
                        {this._getImages()}
                    </div>
                }
            </>
        );
    }

Below is the link to UniteGallery documentation where you can try using different options.

UniteGallery

Preview

Source Code

The source code along with other samples can be found in the below github link.

SPFx-Demos

Happy Coding…

Advertisement

4 thoughts on “SPFx – Using UniteGallery jQuery plugin

  1. Hi,
    Thanks for the post.
    I tried to implement the same in my dev environment and its works fine(both in work bench and sharepoint work bench)

    But when i deployed the same package to PROD environment i am getting below error.

    Unite Gallery Error: You have some jquery.js library include that comes after the gallery files js include.
    This include eliminates the gallery libraries, and make it not work.

    To fix it you can:
    1. In the Gallery Settings -> Troubleshooting set option: Put JS Includes To Body option to true.
    2. Find the double jquery.js include and remove it.

    After checking this I found out there was another control developed by another developer and used jQuery reference and its causing the unite gallery control to break.

    Can you please help me to fix this issue.

    Regards
    Anand

    Liked by 1 person

    • Hi Anand, thanks for trying out the sample. Can you confirm that both the web parts are using the same jQuery version or a different? If they are using a different, can you make it to use the latest? Also, please check on the other web part whether the reference is from the externals section defined in the config.json file

      Let me know the outcome of the above mentioned verfication.

      Cheers…

      Liked by 1 person

  2. Hi Sudharsan,
    Thank you for the detailed article, I tried to setup in my local, and when I try to load the unit gallary webparts, I am getting below error.
    Uncaught ReferenceError: jQuery is not defined
    at ug-theme-slider_7d9eb985d2d3c164e19835ea4e33161e.js:10

    Like

    • Hi Chintan, have you tried my demo sample from github. If you didnt please try. I had mentioned the jquery and unitegallery js files as an externals in the config.json file and also the dependencies. Please check and let me know if you are facing the issue.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s