The ReactJS Slider component represents a versatile Slider that allows the user to choose from a range of values by moving their thumb along a track. The widget's look is totally customizable, and it includes features such as mouse wheel and keyboard support, smooth or step-based sliders, and range slider support.

On the web and in mobile apps, the slider is one of the most common UI elements. It's used to choose a number or a range of values, and it improves the user experience by showing the data associated with the slider.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Prerequisites

Technologies we will be using for this project:

  • ReactJS
  • Bootstrap
  • HTML and CSS
  • react-slider library

Create Your Component

React-slider is a tiny, CSS-agnostic component that allows us to create bespoke slider components for React apps. To create a headless UI for our application, it employs the render props technique.

Make a file called Slider.js to represent our component. We'll need to return each card from our future data, which we may do with the.map() function.

import React, {useState} from 'react'

import './Slider.css'

import dataSlider from './dataSlider'

export default function Slider() {

   return (

        <div className="container-slider">

            {dataSlider.map((obj, index) => {

                return (

                        <img 

                        src={process.env.PUBLIC_URL + `/Imgs/img${index + 1}.jpg`} 

                        />

                )

            })}

        </div>

    )

}

Free ReactJS for Beginners Course

Master the Basics of ReactJSStart Learning
Free ReactJS for Beginners Course

We need to use both the backticks and the $ in order to dynamically refer back to our resources.

process.env.PUBLIC URL, which will be replaced by the URL of our app when we build it. We'll need to add a div containing the img to the css.

<div className="slide">

    <img 

    src={process.env.PUBLIC_URL + `/Imgs/img${index + 1}.jpg`} 

    />

</div>

We must add a key, which is a reference to dataSlider and its many ids, to correct the problem that appears in the console; we may also use the useful "uuid" tool to do so.

<div

    key={obj.id}

    className={slideIndex === index + 1 ? "slide active-anim" : "slide"}

>

 ...

</div>

The various photos are now present; we simply cannot see them. To fix this, double-click the slider and add a component.

<BtnSlider />

<BtnSlider />

Create Button Component

Create a new file called BtnSlider.js that will contain the buttons we'll need to switch between images.

Import the arrows to the left and right. Then, with a classname, make a basic button that contains the image.

import React from "react";

import "./Slider.css";

import leftArrow from "./icons/left-arrow.svg";

import rightArrow from "./icons/right-arrow.svg";

export default function BtnSlider() {

  return (

    <button className="btn-slide">

      <img src={rightArrow} />

    </button>

  );

}

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

To alter the style of our button, we'll construct some state and feed it through the props.

Add a var to your Slider.js file so we can use the state.

const [slideIndex, setSlideIndex] = useState(1)

Create the nextSlide and previousSlide functions, which will be empty for now.

const nextSlide = () => {

}

const prevSlide = () => {

}

Then, using the prop moveSlide, feed it to our component BtnSlider. We must also include the following information:

<BtnSlider moveSlide={nextSlide} direction={"next"} />

<BtnSlider moveSlide={prevSlide} direction={"prev"}/>

Return to our BtnSlider component and remove the props from it. We can check it in the console using a console log.

export default function BtnSlider({ direction, moveSlide }) {

  console.log(direction, moveSlide);

  return (

    <button className="btn-slide">

      <img src={rightArrow} />

    </button>

  );

}

Then, to activate the moveSlide from our props, add an onClick and change the classname of the button to the direction.

<button

      onClick={moveSlide}

      className={direction === "next" ? "btn-slide next" : "btn-slide prev"}

The arrows do emerge now, as we can see. However, they're both the right arrow, which isn't what we want. As a result, we must update the image's source, with the following condition:

<img src={direction === "next" ? rightArrow : leftArrow} />

This is how our complete BtnSlider.js should look:

import React from "react";

import "./Slider.css";

import leftArrow from "./icons/left-arrow.svg";

import rightArrow from "./icons/right-arrow.svg";

export default function BtnSlider({ direction, moveSlide }) {

  console.log(direction, moveSlide);

  return (

    <button

      onClick={moveSlide}

      className={direction === "next" ? "btn-slide next" : "btn-slide prev"}

    >

      <img src={direction === "next" ? rightArrow : leftArrow} />

    </button>

  );

}

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Back to Your Slider

It's now time to alter the classname of the div that displays our photos. Substitute the following code for "slide":

<div

    key={obj.id}

    className={slideIndex === index + 1 ? "slide active-anim" : "slide"}

>

    <img 

    src={process.env.PUBLIC_URL + `/Imgs/img${index + 1}.jpg`} 

    />

</div>

Since the index begins at 0, we must add +1 each time. The css condition is active-anim, which sets the opacity to 1.

Create Logic of the Slider

Let's start by constructing the logic of our functions.

const nextSlide = () => {

        if(slideIndex !== dataSlider.length){

            setSlideIndex(slideIndex + 1)

        } 

        else if (slideIndex === dataSlider.length){

            setSlideIndex(1)

        }

    }

    const prevSlide = () => {

        if(slideIndex !== 1){

            setSlideIndex(slideIndex - 1)

        }

        else if (slideIndex === 1){

            setSlideIndex(dataSlider.length)

        }

    }

If slideIndex is less than 5, the first condition is met, and the next image is displayed.

The second condition checks if we've reached the end of our array, and if we have, the picture will be reset to the first.

Add the Dots at the Bottom of the Slider

To use the.map() function, we'll make an empty array with a length of 5.

<div className="container-dots">

        {Array.from({length: 5}).map((item, index) => (

              <div classname="dot"></div>

         ))}

</div>

However, we do want a dynamic classname, similar to what we achieved with our arrows.

<div

    className={slideIndex === index + 1 ? "dot active" : "dot"}

></div>

Last but not least, it should be possible to click on it and have the image changed.

<div

    onClick={() => moveDot(index + 1)}

    className={slideIndex === index + 1 ? "dot active" : "dot"}

></div>

As a result, we must include this function, which will direct the user to the relevant image.

const moveDot = index => {

        setSlideIndex(index)

}

Now, make sure we use an anonymous function for the onClick; otherwise, the moveDot method will be called when the component is built, which is when the page is loaded, and this is not what we want!

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

Here's how your Slider.js file appears in its entirety:

import React, {useState} from 'react'

import './Slider.css'

import BtnSlider from './BtnSlider'

import dataSlider from './dataSlider'

export default function Slider() {

    const [slideIndex, setSlideIndex] = useState(1)

    const nextSlide = () => {

        if(slideIndex !== dataSlider.length){

            setSlideIndex(slideIndex + 1)

        } 

        else if (slideIndex === dataSlider.length){

            setSlideIndex(1)

        }

    }

    const prevSlide = () => {

        if(slideIndex !== 1){

            setSlideIndex(slideIndex - 1)

        }

        else if (slideIndex === 1){

            setSlideIndex(dataSlider.length)

        }

    }

    const moveDot = index => {

        setSlideIndex(index)

    }

    return (

        <div className="container-slider">

            {dataSlider.map((obj, index) => {

                return (

                    <div

                    key={obj.id}

                    className={slideIndex === index + 1 ? "slide active-anim" : "slide"}

                    >

                        <img 

                        src={process.env.PUBLIC_URL + `/Imgs/img${index + 1}.jpg`} 

                        />

                    </div>

                )

            })}

            <BtnSlider moveSlide={nextSlide} direction={"next"} />

            <BtnSlider moveSlide={prevSlide} direction={"prev"}/>

            <div className="container-dots">

                {Array.from({length: 5}).map((item, index) => (

                    <div 

                    onClick={() => moveDot(index + 1)}

                    className={slideIndex === index + 1 ? "dot active" : "dot"}

                    ></div>

                ))}

            </div>

        </div>

    )

}

Creating a Simple Slider in React

Create a file named slider.js in the root folder and add the following code to start developing a slider in React with the react-slider component:

import ReactSlider from "react-slider";

const Slider = () => {

  return (

    <ReactSlider

      className="horizontal-slider"

      thumbClassName="example-thumb"

      trackClassName="example-track"

    />

  );

};

export default Slider;

It’s completely optional for us to style the slider with the help of cascading style sheet.

Creating a Vertical Slider in React

The react-slider component can also be used to create a vertical slider. Vertical sliders are frequently used to demonstrate progress.

Like horizontal sliders, vertical sliders feature three parts: a step, a slider, and a form.

The Step

To render each of the five steps, create a step.js file and add the following code. We have five steps in the design. As a result, we must provide a steps array with values.

const Step = ({ currentIndex }) => {

  return (

    <div className="steps-container">

      {steps.map((step, index) => {

        let color = currentIndex === index ? "#00d4ff" : "black";

        console.log("color", color);

        return (

          <div className="steps-item">

            <h3

              style={{

                margin: 0,

                color: color

              }}

            >

              {step}

            </h3>

          </div>

        );

      })}

    </div>

  );

};

export default Step;

The currentIndex properties are passed from the parent component here. It stores the value of the slider's presently active element. If the second mark is active, for example, currentIndex is 1.

The Vertical Slider

As designers seek innovative ways to present material, vertical sliders, also known as vertical transitions, have become a modern design trend in recent years to display contents.

Add the following code to Slider/index.js in the root folder to create a vertical slider:

import React from "react";

import ReactSlider from "react-slider";

import "../styles.css";

import "./slider.css";

const Slider = ({ onChange, currentIndex }) => {

  return (

    <ReactSlider

      className="vertical-slider"

      markClassName="example-mark"

      onChange={onChange}

      trackClassName="example-track"

      defaultValue={0}

      value={currentIndex}

      min={0}

      max={4}

      marks

      renderMark={(props) => {

        if (props.key < currentIndex) {

          props.className = "example-mark example-mark-completed";

        } else if (props.key === currentIndex) {

          props.className = "example-mark example-mark-active";

        }

        return <span {...props} />;

      }}

      orientation="vertical"

    />

  );

};

export default Slider;

Now, again as per our choice, we can style the above slider.

Building Form With Progress Slider in React

We can create a form with a progress slider in specific instances, such as creating digital work instructions. Each level comprises a set of inputs that the user must complete, and the progress slider displays the user's progress.

Create Form/index.js and add the following code to begin generating a form:

import React from "react";

import FormElement from "./FormElement";

import "./style.css";

const formEls = ["Step 1", "Step 2", "Step 3", "Step 4", "Step 5"];

const Form = ({ currentIndex, handleNext, handleComplete }) => {

  return (

    <div className="form-container">

      <h3>{formEls[currentIndex]}</h3>

      {currentIndex === formEls.length - 1 ? (

        <FormElement

          value={"Complete"}

          onClick={() => handleComplete(currentIndex)}

        />

      ) : (

        <FormElement value={"Next"} onClick={() => handleNext(currentIndex)} />

      )}

    </div>

  );

};

export default Form;

To manage the stages, the form component uses the currentIndex, handleNext, and handleComplete properties.

Creating Multilevel Form in React

Another approach to using a slider form is to create a multilayer form in an application.

We must utilize styling for horizontal components because the multilevel form employs a horizontal slider. We have marks, min, max, and value props, just as the vertical slider. We don't need a track because this is form-based.

Let's use react-slider and our own stylized components to create a tiered form. On multilevel forms, there are two main components: navigation steps and form elements.

In the component state, we must handle the current index and render the form element based on that index.

<ItemContainer>

    <Fragment>

      {tabs.map((tab, index) => {

        return (

          <FormItem active={state.value === index}>

            <h3>{tabs[index]}</h3>

            <br />

            <Button value={"Next"} onClick={onNext}>

              Next

            </Button>

            <Button value={"Back"} onClick={onPrevious}>

              Back

            </Button>

          </FormItem>

        );

      })}

    </Fragment>

</ItemContainer> 

The Next and Back buttons on the form save the form data in the component state.

const [state, setState] = useState({

    value: 0

  });

  const onNext = () => {

    setState({ ...state, value: state.value + 1 });

  };

  const onPrevious = () => {

    setState({ ...state, value: state.value - 1 });

  };

Finally, there's a slider that displays custom mark and thumb components. To render the custom mark and thumb components in ReactSlider, react-slider provides the renderMark and renderThumb render props.

<ReactSlider

  className="horizontal-slider"

  marks

  min={0}

  max={4}

  value={state.value}

  trackClassName="example-track"

  renderMark={(props, state) => {

    return (

      <FormLevel>

        <FormLevelLabelContainer

          {...props}

          firstChild={true}

          active={false}

        >

          <FormLevelLabelText>{tabs[props.key]}</FormLevelLabelText>

        </FormLevelLabelContainer>

      </FormLevel>

    );

  }}

  renderThumb={(props, state) => {

    return (

      <FormLevel {...props} active={state.valueNow === state.value}>

        <FormLevelLabelContainer

          firstChild={true}

          active={state.valueNow === state.value}

        >

          <FormLevelLabelText>

            {tabs[state.valueNow]}

          </FormLevelLabelText>

        </FormLevelLabelContainer>

      </FormLevel>

    );

  }}

/>

Comparing React Slider Components

There are more alternatives to employ when creating a slider with React. The following is a quick rundown of each, as well as its advantages and limitations.

  • Material -UI

Material-UI is a well-known UI framework with a minified bundle size of roughly 300Kb and a download time of 13ms; its slider package, material-ui-slider, has a minified bundle size of 26Kb and a download time of 1ms. The development community loves Material UI because of its beginner-friendly documentation and ability to inspect the whole source code in its built-in editor. However, utilizing material-ui-slider can increase the size of an application's bundle, and customization is not as extensive as it is with react-slider.

  • Ant-Design

Ant Design, a UI design language and React UI framework, is also quite popular, but it suffers from the same issue of a larger bundle size (2.2Mb minified), which might cause issues when constructing sliders.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

The slider is a typical React UI element that displays a range of values, allowing users to rapidly select from a variety of possibilities. While there are other libraries and frameworks for creating a slider, the react-slider component offers customizability, a compact bundle size for optimal performance, and a developer-friendly interface. It's also worth noting that if our product or organization currently uses a framework or library like Ant Design, Bootstrap, or Material UI, using slider components from those frameworks is easier.

If you are interested in learning more about ReactJS and other related concepts, you can enroll in Simplilearn’s exclusive Full Stack Web Development Certification Course and accelerate your career as a software developer. The program comprises a variety of software development courses, ranging from the fundamentals to advanced topics. 

Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. You can take up any of these courses to upgrade your skills and advance your career.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.