Custom Image Slider in Salesforce Using Lightning Web Component

In Salesforce Lightning pages, we can use image sliders to make them more attractive and interactive. An image slider allows us to display images with transitions and add captions.

In Salesforce, we can display image sliders using different methods, such as:

  • Using inbuilt lightning-carousel element
  • Using an external JS library such as Flickity

In this tutorial, I will show you how to create an image slider in Salesforce using the above two methods with examples.

Custom Image Slider in Salesforce Using Lightning Web Component

An image slider in Salesforce is a Lightning component that displays an image slideshow. It can be deployed on the Lightning record page, home page, and community page. The displayed images are fetched from static resource files or publicly available external URLs.

First, we will create an image slider in Salesforce using the inbuilt lightning-carousel element.

Using Lightning-Carousel

We need to create a lightning web component to display slider images using the standard lightning-carousel element.

Follow the below steps:

  1. Open the VS code IDE integrated with your Salesforce org, then press the keys ctrl+shift+p to open the Command Palette. Type SFDX and select SFDX: Create Lightning Web Component.
Create Image Slider using LWC in Salesforce
  1. Then, provide a name for the component and press enter.
Standard Carousel in Lightning web component
  1. This will create the lightning web component. It will generate three files (HTML, JS, and meta.xml) like the screenshot below:
Custom Image Slider in Salesforce using LWC

In the next step, we need to add the lightning-carousel element to the HTML file to display the image slider.

By default, the HTML file will have the <template></template> tag.

Paste the below code inside the <template> tag to define the UI.

<template>
    <lightning-card title="LWC Carousel"></lightning-card>
    <div class="slds-size_3-of-4">
        <div class="slds-box slds-box_x-small slds-text-align_center slds-m-around_x-small">Lightning Web Component Carousel
            <lightning-carousel>
                <lightning-carousel-image
                    src = "https://www.lightningdesignsystem.com/assets/images/carousel/carousel-01.jpg"
                    header = "First Card"
                    description = "First card description."
                    alternative-text = "First card accessible description.">
                </lightning-carousel-image>
                <lightning-carousel-image
                    src = "https://www.lightningdesignsystem.com/assets/images/carousel/carousel-02.jpg"
                    header = "Second Card"
                    description = "Second card description."
                    alternative-text = "Second card accessible description.">
                </lightning-carousel-image>
                <lightning-carousel-image
                    src = "https://www.lightningdesignsystem.com/assets/images/carousel/carousel-03.jpg"
                    header = "Third Card"
                    description = "Third card description."
                    alternative-text = "Third card accessible description.">
                </lightning-carousel-image>
            </lightning-carousel>
        </div>
    </div>
</template>

Here, we have used the lightning-carousel to define the slider image section. Inside that, we have used the lightning-carousel-image element to add the images in the slider.

For the image source (src), we have used the image links from lightningdesignsystem.com. You can provide any link to the image here that is publicly available.

You can add a header, description, and alternative text inside the lightning-carousel-image tag.

We do not need to modify anything in the JS file. The JS code looks like below:

import { LightningElement } from 'lwc';
export default class CarouselComponent extends LightningElement {}

To make the component visible to the Lightning pages, enter the code below in the meta.xml file.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

Once this is over, we can deploy the lightning web component to the org.

Follow the below steps:

  1. To deploy the changes, right-click on the LWC file and select deploy this source to org.
Salesforce LWC image slider
  1. To display the Lightning web component, navigate to the Lightning page, click on the settings icon, and select the Edit page.
  2. In the Lightning app builder, drag and drop the carousel lightning web component to the page region and save the changes.
Lightning Carousel element in LWC

Now, you will see the image slider in the Lightning Web Component, where we can view the sliding images.

Salesforce Lightning Carousel element

This way, we can add an Image Slider in the lightning web component using the lightning-carousel element.

Using External JS Library Flickity

The standard lightning carousel is easier to use within Salesforce LWC, but its features are limited; for example, we can add a maximum of 5 panels, but only one panel is visible at a time.

We use the JS library flickity to get advanced features like swipe gestures, lazy loading, and better performance control. Unlike the standard lightning-carousel, we can add more than five panels in the image slider.

For this, we have to download the library and add it as a static resource in Salesforce.

Navigate to the link https://flickity.metafizzy.co/, download the zipped folder, and name it flicking. The folder contains the JS file flickity.pkgd.min.js and the CSS file flickity.css.

Js library to create image slider in Salesforce

Ensure that the downloaded folder structure is like Zipped Flickity folder > Library files and not like Zipped Flickity folder> Flickity folder > Library files.

Now, to use this library, we need to create a static resource for it. Navigate to setup> quick find > static resources.

Static Resource to create image slider in Salesforce

In the new static resource, enter the Name, and in the File, select the downloaded zipped folder.

Select the Cache Control as Public and click on the Save button.

Image Slider JS library in Salesforce LWC

With this, we have created the static resource for the JS library, which we can now use in the Lightning web component to create the custom image slider.

Creating the Lightning Web Component:

Follow the steps below to create an image slider in the Lightning Web Component using the JS library Flickity.

  1. In the VS code, press the keys ctrl+shift+p to open the Command Palette. Type SFDX and select SFDX: Create Lightning Web Component.
  2. Give a custom label to the component, such as flickityCarousel and press the Enter key.

This will create a lightning web component with the HTML, Javascript, and meta.xml files.

Add Custom image slider in Lightning web component
  1. Now, we need to define the logic to get the image slider from js library that we have saved in the static resource.

The logic to fetch or get data or import any class and resource is defined in the JS file in the Lightning web component. Enter the code below in the JS file to import the image slider library.

import { LightningElement } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import FLICK from '@salesforce/resourceUrl/flickity';

export default class FlickityCarousel extends LightningElement {
    flickityInitialized = false;

    renderedCallback() {
        if (this.flickityInitialized) return;
        this.flickityInitialized = true;

        Promise.all([
            loadScript(this, FLICK + '/flickity.pkgd.min.js'),
            loadStyle(this, FLICK + '/flickity.css')
        ])
        .then(() => {
            const elem = this.template.querySelector('.carousel');
            new Flickity(elem, {
                cellAlign: 'left',
                contain: true,
                autoPlay: 1500,
                wrapAround: true,
                imagesLoaded: true
            });
        })
        .catch((error) => {
            console.error('Flickity load error:', error);
        });
    }
}

In the above code, the LWC loads the Flickity carousel library (JS and CSS) from a static resource using loadScript and loadStyle.

In the renderedCallback, it initializes a Flickity carousel on a .carousel element with options like left-aligned cells, autoplay every 1.5 seconds, infinite looping, and image loading.

For error handling, I have also added a debug code:

.catch((error) => {
            console.error('Flickity load error:', error);
        });

If the JS library will not load, this debug log will return an error in the console.

  1. To render the image slider’s UI, enter the code below in the HTML file inside the <template> tag.
<template>
    <lightning-card  title="Flickity Caraousel images">
        <div class="gallery-cell">
            <img src="https://d1.awsstatic.com/s3-text-media-grid-3-s3-overview-1.5a165ee4fd9f44bd2f0b1a88ec662223479f0d9f.jpg" alt="submerged" />
        </div>
        <div class="gallery-cell">
            <img src="https://d1.awsstatic.com/text-media-grid-4-s3-overview-1.f95a3222dfb708f6146afab8b14705ffa79e99ce.jpg" alt="look-out" />
        </div>
        <div class="gallery-cell">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/one-world-trade.jpg" alt="One World Trade" />
        </div>
        <div class="gallery-cell">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/drizzle.jpg" alt="drizzle" />
        </div>
        <div class="gallery-cell">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/cat-nose.jpg" alt="cat nose" />
        </div>
      </div>
  </lightning-card>
  </template>

In the above code, we have used the <lightning-card> tag to add the title in the lightning component.

Inside the <div class=”carousel”>, we have added five <div class=”gallery-cell”>
elements each contain a URL image for the carousel slides.

  1. In the same lightning web component, create a CSS file, flickityCarousel.CSS.
Add css to Lightning carousel in Salesforce

We are adding this CSS to arrange the images because they may have different sizes. To arrange the images, enter the code below in the CSS file.

.carousel {
    background: #EEE;
  }
  
  .gallery-cell {
    width: 70%; 
    margin-right: 10px;
  }
  
  .carousel img {
    display: block;
    height: 200px;
    width: 100%;
    object-fit: cover;
  }
  
  @media screen and (min-width: 768px) {
    .carousel img {
      height: 400px;
    }
  }

After this, also add this class in the js file as:

<template>
    <lightning-card  title="Flickity Caraousel images">
      <div class="carousel">
        <div class="gallery-cell">

.(rest of the code)

<template>
  1. At last, expose the component to the lightning pages using the code below in the meta.xml file.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

How will the code inside this lightning web component work and display images in the carousel slider?

So, the JavaScript loads Flickity’s JS and CSS, then initializes the carousel (HTML) on the .carousel div (CSS) with autoplay (1.5s), infinite looping, and left-aligned slides, ensuring images load properly before display.

This completes the lightning web component with the logic of displaying the image slider using the external JS library.

Now, deploy the source code to the org. To do that, press ctrl+shift+p, then in the command palette, search and select deploy this source to org.

LWC with Lightning Carousel in Salesforce

Navigate to the Lightning page and deploy this lightning web component to view the image slider.

Create Custom Carousel in Salesforce LWC

Display Images Using Static Resource in LWC Image Slider

We have displayed the images in the Lightning image slider in the above examples using the URL links. Here, we can add static images in the Lightning carousel or the image slider.

To display the static images in the image slider, we have to create the static resource in the Salesforce org. From there, we can fetch the images stored in the lightning component, exactly what we did for the JS library in the previous example.

Follow the below steps to create the static resource for the images.

  • Navigate to the Salesforce setup, and in the quick find search, select Static resources.
  • Click on the New button in the setup. In the next window, enter the label as StaticImage.

After this upload, the zipped version of the image folder set the cache control as Public.

Display static image in LWC image slider

Ensure that images inside the zip folder are saved as Static images.zip > image files, not like Static images.zip > Static images > image files.

Now, we will create a lightning web component importing the static images and displaying them in the lightning-carousel.

  1. Create a Lightning Web Component and enter the below code in the JS file to get the images from the Static resource.
import { LightningElement } from 'lwc';
import staticImages from '@salesforce/resourceUrl/StaticImage';

export default class StaticImageSlider extends LightningElement {
    img1 = '${staticImages}/img1.png';
    img2 = '${staticImages}/img2.png';
    img3 = '${staticImages}/img3.jpg';
}
  1. To define the LWC’s UI with an image slider, enter the code below in the HTML file.
<template>
    <lightning-card title="Image Carousel using Static Resource">
        <lightning-carousel>
            <lightning-carousel-image
                src={img1}
                header="First Image"
                description="This is image 1"
                alternative-text="Image 1">
            </lightning-carousel-image>

            <lightning-carousel-image
                src={img2}
                header="Second Image"
                description="This is image 2"
                alternative-text="Image 2">
            </lightning-carousel-image>

            <lightning-carousel-image
                src={img3}
                header="Third Image"
                description="This is image 3"
                alternative-text="Image 3">
            </lightning-carousel-image>
        </lightning-carousel>
    </lightning-card>
</template>

In this, we have used the lightning-carousel element to define the image slider, and within that, we have used the lightning-carousel-image element to add the images.

Here, we have referred to the image source from the JS file as src {image_name}, which we defined by fetching the images from the static resource.

  1. Make the component visible to the lightning pages using the code below in the meta.xml files.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

Now, deploy the lightning web component on the Lightning page, and there you will see the images in the LWC image slider with the images that we have added in the static resource.

Add static images to lightning carousel

This way, we can display static images in the lightning Web Component image slider (lightning-carousel).

Conclusion

The lightning-carousal element is useful when displaying less than five images in an image slider because it supports five images simultaneously. To display more than five images and have more control on the slider like forward and backward arrow to control slide moment using the JS library such as Flickity is an ideal solution.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.