While working on Community Portal, sometimes we have to show images or content as a slider component. We have a lightning carousel element but there are limitation on standard carousel elements. This post will give step-by-step detail to create a custom image slider in Lightning Web Component.
To create a custom image slider (image carousel) in Salesforce, I am using external Js library – flickity. There are many other slider libraries like Slick, Owl Carousel 2, BxSlider, and GliderJS. Best on your preference and requirement, you can choose any external js.
Steps to create Custom Image Carousel in LWC
- Download flickity JS library
- Add required files to static resources
- Create LWC component
- Test component
1. Download flickity JS library
Download the below files from https://flickity.metafizzy.co/.
- JS file flickity.pkgd.min.js
- CSS file flickity.css
This library requires jQuery so download it from https://cdnjs.com/libraries/jquery/3.0.0
Add all the above three files into the flickity.zip file.
2. Add required files to static resources
Add the above-created flickity.zip into the static resource as flickity. Set Cache-Control as public for this static resource.
3. Create Lightning Web component
We have added the required JS and CSS files in the static resource. Let us create an LWC component to create an image carousel using these files. This library has options to create any type of slider. For demo purposes, I have created a component that has images, images with text, and only text slides.
We have to import static resources and run the below code to start the image slider.
// slider options. Checkout other options form website
Below code will be added to the component to create the custom slider. Setup options based on your requirement like autoplay time.
4. Test component
Add the above-created component where you want to give image slide capability. I have added that on the Home page.