Pelumi Akintokun Frontend developer and technical writer who is passionate about the web. Creator of websites that tell stories.

Building a draggable slider in React

8 min read 2519

Build a Draggable Slider in React

Website sliders are flexible user interface elements that can be helpful for sharing multiple images or conveying information efficiently without wasting valuable space on your homepage.

In this article, we’ll demonstrate how to use the react-draggable-slider package to build a slider with draggable functionality in React.

Jump ahead:

What is a slider?

A website slider is a slideshow that displays a series of images or items that are arranged horizontally or vertically within a single space. The images are displayed individually over a defined time period with a transition effect between the change from one image or item to the next.

A user can navigate through the slider images using a set of navigation controls, and the images or items can also be looped through. A slider can help a website showcase individual items in a visually appealing way while also saving screen space.

Website sliders that showcase customer testimonials can be advantageous for building trust and credibility with new prospects. Sliders may also be used to display different service offerings or show multiple images of a product so a potential customer can visualize it from different angles.

This type of UI element is an attractive option to a long page of scrolling content. With a slider, you can group information in one place, set a comfortable pace for cycling between each item, and even add an auto-play feature.

What is a draggable slider?

Draggable sliders are navigated manually; the user navigates from one item to the next by holding and dragging the item that is currently in view to the left or right. To view the next item, the user holds and drags the current item to the left. Likewise, to view the previous item, the user holds and drags the current item to the right.

What is react-draggable-slider?

To create a draggable slider in React, we can either build it from scratch or use a React package.

Using a React package may improve your productivity, as it will reduce the time you spend writing code. However, it does mean that your codebase will be dependent on (and perhaps vulnerable to) the package. This is why it’s preferable to select an open source package that has a large community contributing to it, finding, reporting, and fixing bugs, and thus keeping the code secure.



For this article, we’ll use the react-draggable-slider package. This package is easy to use and comes with an inbuilt hover effect.

React draggable slider demo

To demonstrate building a draggable slider in React, we’ll set up a React app, install the react-draggable-slider package, and then create the slider and define the slider settings.

Let’s get started!

Creating the React app

Use the following command to create a React app and name it react-draggable-slider:

npx create-react-app react-draggable-slider

Now, open the app in the code editor of your choosing. In this demo, I’ll use VS Code.

Installing the react-draggable-slider package

At the time of writing, the react-draggable-slider package is not compatible with React v18, which is the version of React we’ll get when we create the React app.

So, if we try to install the slider package right now using command: npm i react-draggable-slider, it won’t be installed and we’ll get a dependency conflict error in our terminal, as shown below:

Dependency Conflict Error

As a workaround, we’ll need to downgrade the versions of the react package and react-dom package in our React app to v16 in order to be compatible with the react-draggable-slider package.

There’s no way to specify the desired React version when creating the app, which is why we needed to create the app before downgrading the version.


More great articles from LogRocket:


First, navigate into the package.json file and change the versions of the react package and react-dom package from v18.1.0 to v16.13.1.

Next, run the command: npm install in the terminal. This will automatically replace the current versions in our node_modules folder with the new one we specified in the package.json file.

Now we’re ready to install the slider package:

npm i react-draggable-slider

At this time, we should not see any errors in our terminal. To view the app in the browser, run the React app using either of the below commands:

npm start
yarn start

You’ll notice in the browser there’s a new error about the react-dom/client React module not being found. This error is occurring because we’re using React v16.

Module Not Found Error

To address this error, we’ll need to make some modifications to our index.js file by changing the file path of the module.

Navigate into the index.js file and change the file path of the ReactDom import from:

import ReactDOM from 'react-dom/client';

to:

import ReactDOM from 'react-dom';

Next, we need to adjust how we render our React app to the DOM. To do this, change the code used to render the React app from:

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

to:

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

Now, go back and view the app in your browser. You should see the contents of the app without any errors:

App Without Errors

OK, we’ve created our app; now it’s time to create our draggable slider.

Creating the slider

To build the slider, go into the App.js file and delete the current jsx element (i.e., the Header) since it is not needed. We’ll replace this element with the Slider component that we’ll import from react-draggable-slider. We’ll also pass a sliderSettings object as a prop into our Slider component that we’ll create later.

import Slider from "react-draggable-slider";

…

<div className="App">
     <Slider sliderSettings={sliderSettings} />
</div>

Next, we’ll create an array of objects called projectList. We’ll use this array to store the items that will be displayed on each slide in the slider.

const projectList = [
    {
      title: "Nature's Life",
      image: project1,
      description:
        "Praesent quis congue nisi. Vivamus dapibus suscipit magna at imperdiet. Mauris consectetur pharetra metus eu suscipit. Maecenas augue tortor, consequat vitae lacus id, pharetra tempor mauris. Suspendisse sodales commodo erat, non imperdiet nisl scelerisque at. Nulla porttitor gravida diam, in ornare ipsum accumsan bibendum. Morbi ut ante metus. "
    },
    {
      title: "Into The Waters",
      image: project2,
      description:
        "Duis at tellus vitae velit aliquet varius. Fusce luctus libero et ligula tristique lobortis. Vestibulum eu placerat risus, eu semper augue. Integer at purus sit amet elit pretium viverra. Suspendisse id fringilla nibh, nec dictum urna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. "
    },
    {
      title: "Higher Than The Stars",
      image: project3,
      description:
        "Praesent quis congue nisi. Vivamus dapibus suscipit magna at imperdiet. Maecenas augue tortor, consequat vitae lacus id, pharetra tempor mauris. Suspendisse sodales commodo erat, non imperdiet nisl scelerisque at. Nulla porttitor gravida diam, in ornare ipsum accumsan bibendum. Morbi ut ante metus. Proin rhoncus magna lectus, nec consequat augue ultricies eu."
    },
    {
      title: "Miniature Wonders",
      image: project4,
      description:
        "Praesent quis congue nisi. Vivamus dapibus suscipit magna at imperdiet. Mauris consectetur pharetra metus eu suscipit. Maecenas augue tortor, consequat vitae lacus id, pharetra tempor mauris. Suspendisse sodales commodo erat, non imperdiet nisl scelerisque at. Nulla porttitor gravida diam, in ornare ipsum accumsan bibendum. Morbi ut ante metus. "
    },
    {
      title: "Giants Of History",
      image: project5,
      description:
        "Duis at tellus vitae velit aliquet varius. Fusce luctus libero et ligula tristique lobortis. Vestibulum eu placerat risus, eu semper augue. Integer at purus sit amet elit pretium viverra. Suspendisse id fringilla nibh, nec dictum urna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. "
    }
  ];

Defining the slider settings

Now, we’ll define our slider settings; these will be passed into our slider to configure its behavior.

We’ll start by creating an object called sliderSettings which has the following props: data, speed, easing, bgColor, showButton, buttonText, buttunHref, and buttonTarget. These props define how our slider will behave and how it will be displayed.

data

The data prop accepts an array. The array of objects represents the details of the items or slides in the slider that will be displayed; in our case, the projectList. Each object accepts three key-value pairs: title, image, and description. By default, the data prop is set to an empty array, [].

speed

The speed prop accepts an integer. It determines the speed (in milliseconds) at which the slider should progress when dragged to the next or previous item. As an example, a speed value of 3000 equals 3 sec. The default speed prop value is 500ms.

easing

The easing prop accepts a string. There are four available GSAP easings used to animate sliding: power, back, elastic, and expo. Try each of them, and then choose the one you like best. If no value is specified, the easing prop value will default to ease which is the default value of the browser.

bgColor

The bgColor prop accepts a string. It sets the background color of the whole slider and accepts HEX and RGB(A) values. For example, #ffffff or rgba(255, 255, 255, 0.05). The default value of the bgColor prop is rgba(255, 255, 255, 0.05).

showButton

The showButton prop accepts a Boolean. If set to true, a button will be shown for each item or slide; however, no button will be shown if the showButton prop is set to false. By default, the showButton prop value is set to true.

buttonText

The buttonText prop accepts a string. It represents the text that will be displayed inside the button for each item. By default, the value is set to View case study.

buttonHref

The buttonHref prop accepts a string. This string is a href attribute that allows each item in the slider to link to another page, enabling the user to view additional details about the item. By default, the buttonHref prop value is set to #.

buttonTarget

The buttonTarget prop accepts a string. When the user clicks on a button, this prop specifies if the link should open on the current page or on a different page. The value can either be _self or _blank. By default, the buttonTarget prop value is set to _blank.

Let’s begin by passing in only the data prop to see what our slider would look like.

const sliderSettings = {
    data: projectList,
  };

If we view our slider in the browser, we can see that it has the default react-draggable-slider props as described earlier. Now, let’s pass on the rest of our props with our preferred values. Since we’re not specifying a value for the easing prop, it will default to ease.

const sliderSettings = {
    data: projectList,
    speed: 3000,
    bgColor: "#070707",
    showButton: true,
    buttonText: "View projects",
    buttonHref: "https://www.example.com",
    buttonTarget: "_self"
  };

We’ll also write some stylings in our styles.css file for our body and anchor tag, which is also our call to action button, and then import the file into our App.js file.

body {
  font-family: sans-serif;
  text-align: center;
  background-color: #070707;
  color: #fff;
}
a:link,
a:hover,
a:active,
a:visited {
  color: #eee;
  border-top: 1px solid #434141;
  border-bottom: 3px solid #434141;
  border-radius: 20px;
}

At this point, our App.js file should look like this:

import React from "react";
import Slider from "react-draggable-slider";
import "./styles.css";
import project1 from "./imgs/bibi-pace-Hi4fWKU2KSk-unsplash.jpg";
import project2 from "./imgs/scott-webb-e3dY8laAQtA-unsplash.jpg";
import project3 from "./imgs/alexander-andrews-fsH1KjbdjE8-unsplash.jpg";
import project4 from "./imgs/daan-mooij-RyxShs7mG8E-unsplash.jpg";
import project5 from "./imgs/damien-santos-M5rim8Yh4LY-unsplash.jpg";

export default function App() {
  const projectList = [
    {
      title: "Nature's Life",
      image: project1,
      description:
        "Praesent quis congue nisi. Vivamus dapibus suscipit magna at imperdiet. Mauris consectetur pharetra metus eu suscipit. Maecenas augue tortor, consequat vitae lacus id, pharetra tempor mauris. Suspendisse sodales commodo erat, non imperdiet nisl scelerisque at. Nulla porttitor gravida diam, in ornare ipsum accumsan bibendum. Morbi ut ante metus. "
    },
    {
      title: "Into The Waters",
      image: project2,
      description:
        "Duis at tellus vitae velit aliquet varius. Fusce luctus libero et ligula tristique lobortis. Vestibulum eu placerat risus, eu semper augue. Integer at purus sit amet elit pretium viverra. Suspendisse id fringilla nibh, nec dictum urna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. "
    },
    {
      title: "Higher Than The Stars",
      image: project3,
      description:
        "Praesent quis congue nisi. Vivamus dapibus suscipit magna at imperdiet. Maecenas augue tortor, consequat vitae lacus id, pharetra tempor mauris. Suspendisse sodales commodo erat, non imperdiet nisl scelerisque at. Nulla porttitor gravida diam, in ornare ipsum accumsan bibendum. Morbi ut ante metus. Proin rhoncus magna lectus, nec consequat augue ultricies eu."
    },
    {
      title: "Miniature Wonders",
      image: project4,
      description:
        "Praesent quis congue nisi. Vivamus dapibus suscipit magna at imperdiet. Mauris consectetur pharetra metus eu suscipit. Maecenas augue tortor, consequat vitae lacus id, pharetra tempor mauris. Suspendisse sodales commodo erat, non imperdiet nisl scelerisque at. Nulla porttitor gravida diam, in ornare ipsum accumsan bibendum. Morbi ut ante metus. "
    },
    {
      title: "Giants Of History",
      image: project5,
      description:
        "Duis at tellus vitae velit aliquet varius. Fusce luctus libero et ligula tristique lobortis. Vestibulum eu placerat risus, eu semper augue. Integer at purus sit amet elit pretium viverra. Suspendisse id fringilla nibh, nec dictum urna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. "
    }
  ];

  const sliderSettings = {
    data: projectList,
    speed: 3000,
    easing: "ease",
    bgColor: "#070707",
    showButton: true,
    buttonText: "View projects",
    buttonHref: "https://www.example.com",
    buttonTarget: "_self"
  };

  return (
    <div className="App">
      <Slider sliderSettings={sliderSettings} />
    </div>
  );
}

Here’s the slider with its new CSS styles:

You’ll notice that we’ve changed the text color, as well as the background color of the page and slider. We’ve also styled the button and changed its text value. If we use the power GSAP easings to animate the sliding, the sliding animation will look like this:

You can try out the other easing prop options on your own and choose the one you like best and also experiment with the other props values.

You’ll also notice that the image cards have a nice hover effect when the cursor is moved over them. This is a cool, inbuilt feature of react-draggable-slider.

Conclusion

In this tutorial, we showed how easy it is to create a draggable slider in React using the react-draggable-slider package. We demonstrated how to compensate for a compatibility issue with the most recent version of React. We also showed how to modify the default settings of react-draggable-slider to customize the styling and animation of our slider.

Feel free to view and play with the code here. You may also want to check out another React slider tool, Swiper, which is a very cool package as well.

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Pelumi Akintokun Frontend developer and technical writer who is passionate about the web. Creator of websites that tell stories.

2 Replies to “Building a draggable slider in React”

Leave a Reply