ReactHustle

How to Create a React Image Slider Component

Jasser Mark Arioste

Jasser Mark Arioste

How to Create a React Image Slider Component

Hello, hustlers! In this tutorial, you'll learn how to create a react image slider component by using the EmblaCarousel package to control the component and TailwindCSS for styling. We'll also use NextJS as our react framework so if you're using another framework, be sure to install TailwindCSS correctly for that framework.

Why Use EmblaCarousel? #

EmblaCarousel is a lightweight, open-source, carousel library with fluid motion and great swipe precision.

I like to use EmblaCarousel because it's lightweight, it has typescript support, it is well-documented, and it allows for maximum flexibility when creating components. 99% of the time, you can use EmblaCarousel to create image sliders to support any project requirements.

Step 1: Project Setup #

In this step, we'll use the create-next-app CLI to initialize a new NextJS Project. With version 13.x, the folks at NextJS made it incredibly easy to include TailwindCSS. Just run the following command:

npx create-next-app --ts --tailwind --use-yarn --app react-image-slider-tutorial

The above command initializes the project with Typescript, Tailwind, and Yarn. To know more about the options available, you can run npx create-next-app --help.

Step 2: Installing EmblaCarousel #

Since we're using React, we're going to install the embla-carouse-react package using the following command:

# yarn
yarn add embla-carousel-react
# npm
npm install embla-carousel-react --save

Step 3: Creating the <ImageSlider/> component #

In this step, we'll create the container <ImageSlider/> component. First, create the file components/ImageSlider.tsx.

// components/ImageSlider.tsx
"use client";
import useEmblaCarousel, { EmblaOptionsType } from "embla-carousel-react";
import { PropsWithChildren } from "react";

// Define the props
type Props = PropsWithChildren & EmblaOptionsType;

const ImageSlider = ({ children, ...options }: Props) => {
  // 1. useEmblaCarousel returns a `emblaRef` and we must attach the ref to a container element like a div.
  // EmblaCarousel will use that ref as basis for swipe and other functionality.
  const [emblaRef] = useEmblaCarousel(options);

  return (
    // Attach ref to a div
    // 2. The wrapper div must have overflow:hidden
    <div className="overflow-hidden" ref={emblaRef}>
      {/* 3. The inner div must have a display:flex property for horizontal scrolling*/}
      {/* 4. We pass the children as-is so that the outside component can style it accordingly */}
      <div className="flex">{children}</div>
    </div>
  );
};
export default ImageSlider;
123456789101112131415161718192021222324

Explanation:

The embla-carousel-react package default exports the useEmblaCarousel custom hook. This hook accepts EmbleOptionsType and returns a ref. You then attack this ref to the container div element.

The ImageSlider component itself accepts children from PropsWithChildren type and options from EmblaOptionsType type. This will make the usage of the ImageSlider component much easier later on.

Step 4: Usage #

Next, we can now use the component to render images.

import ImageSlider from components/ImageSlider";

export default function Component() {
  // url images
  const images = [
    "https://source.unsplash.com/random/480x240/?mountain",
    "https://source.unsplash.com/random/480x240/?fruit",
    "https://source.unsplash.com/random/480x240/?people",
    "https://source.unsplash.com/random/480x240/?dogs",
    "https://source.unsplash.com/random/480x240/?cat",
    "https://source.unsplash.com/random/480x240/?mountain",
    "https://source.unsplash.com/random/480x240/?fruit",
    "https://source.unsplash.com/random/480x240/?people",
    "https://source.unsplash.com/random/480x240/?dogs",
    "https://source.unsplash.com/random/480x240/?cat",
  ];

  return (
    <main className="p-10">
      <ImageSlider>
        {images.map((imageUrl, i) => (
          <img key={i} src={imageUrl} />
        ))}
      </ImageSlider>
    </main>
  );
}
123456789101112131415161718192021222324252627

That's basically it!

Demo #

Here's the demo:

React Image Slider Component Tutorial

Full Code #

The full code can be accessed at Github: jmarioste/react-image-slider-component-tutorial

Conclusion #

You learned how to create an ImageSlider component in React by using EmblaCarousel and TailwindCSS. This example is very basic, but you can add more components such as thumbnails, dots, and arrows for your component. Be sure to go to the EmblaCarousel documentation for more examples.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on GitHub.

Resources #

Credits: Image by Jon Pauling from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle