Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Enhancing Your React Slider for A Remarkable User Experience

A slider is a commonly used user interface (UI) element in software applications. It allows users to select a specific value within a specified range, empowering them to make choices, set preferences, and navigate options seamlessly.

Early implementation of slider interactivity with HTML and JavaScript had limited customization options and functionality. However, with the emergence and evolution of JavaScript frameworks like React, developers acquired the flexibility to integrate custom slider components. These React sliders provide an intuitive and visually appealing approach to interacting with data in a way that enhances the user experience.

This article will delve into understanding React sliders, basic implementation, delving into advanced customization options with React slider libraries, and exploring React slider management, accessibility options, and benefits.

What is a React Slider?

A slider in React is a customizable UI component that allows users to interact with a range of data by dragging a handle along a track. It is a native HTML input element with the `type` of range. The range of the slider element is from 0 to 100 or 0 to 1 by default. React provides state management features to dynamically update the slider’s value through the `value` and `onChange` props. Moreover, it supports other props for the range, aesthetics, and interactivity of the slider component, including:

  • step: The step value specifies the interval by which the slider changes.

  • defaultValue: This sets the initial value of the slider.

  • min: This sets the minimum value of the slider’s range.

  • max: This specifies the maximum value of the slider.

  • className: The class name prop enables us to customize the slider appearance.

Effectively applying these props ensures the slider reflects the data we want the user to visualize, improving the user experience. In the subsequent section, let’s apply these props to build a basic slider.

Before we delve in, visit Purecode AI and explore how our AI-powered code automation platform improves your workflow by generating customizable UI components to suit your React project needs.

Basic Implementation of React Slider

A basic implementation of the React slider involves using the native HTML `<input type=”range” />` along with React state management. Consider the following example while a basic custom slider component:

// Slider.js

import React, { useState } from "react";

const Slider = () => {
  const [value, setValue] = useState(0);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <div>
      <input
        type="range"
        value={value}
        step={1}
        min={0}
        max={10}
        onChange={handleChange}
      />
    </div>
  );
};

export default Slider
import Slider from "./Slider"

function App() {
  return (
    <>
      <Slider />
    </>
  );
}

export default App;

In the code above, we specified the range by setting the value of the `max` and `min` props. We also let React handle the slider state by specifying the `value` and `onChange` props. The result is illustrated below:

Advanced Slider Customization with React Slider Libraries

The React ecosystem provides several libraries to enhance the slider’s visual appeal and functionality. They support additional features and customization options for creating an intuitive and interactive slider element. These libraries include the following:

  • `react-slider`

  • `rc-slider`

  • `rsuite` slider

  • `material-ui` slider

Utilizing react-slider

The `react-slider` library is an accessible, CSS agnostic, slider component for React. It supports additional props that give us the flexibility to customize the slider in a user-friendly way. The most popular `react-slider` component props include the following:

  • The `thumbClassName` prop, is the CSS class set for the thumb nodes.

  • The `trackClassName` prop, is the CSS class set between the thumbs.

  • The `renderThumb` prop, receives a custom render function that accepts two arguments, a props object that should be added to your handle node, and an object with a thumb and slider state.

Consider the following example when building a slider with the `react-slider` library:

  • A single slider

    // styles.css
    
    .horizontal-slider {
      width: 100%;
      max-width: 500px;
      height: 50px;
      border: 1px solid grey;
    }
    
    .horizontal-slider .example-track {
      top: 20px;
      height: 10px;
    }
    .example-track {
      background: rgb(221, 221, 221);
    }
    
    .example-track.example-track-1 {
      background: rgb(255, 0, 0);
    }
    
    .example-thumb {
      font-size: 0.9em;
      text-align: center;
      background-color: black;
      color: white;
      cursor: pointer;
      border: 5px solid gray;
      box-sizing: border-box;
    }
    
    .horizontal-slider .example-thumb {
      top: 1px;
      width: 50px;
      height: 48px;
      line-height: 38px;
    }
    import React, { useState } from "react";
    import ReactSlider from "react-slider";
    
    import "./styles.css";
    
    function App() {
      return (
        <div>
          <ReactSlider
            className="horizontal-slider"
            thumbClassName="example-thumb"
            trackClassName="example-track"
            renderThumb={(props, state) => <div {...props}>{state.valueNow}</div>}
          />
        </div>
      );
    }
    
    export default App;
    A simple slider with a red track and dark thumb
  • Multi slider

    // styles.css
    
    * {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }
    
    body {
      font-family: "Roboto", sans-serif;
    }
    
    .horizontal-slider {
      width: 100%;
      max-width: 500px;
      height: 50px;
      border: 1px solid grey;
    }
    
    .example-thumb {
      font-size: 0.9em;
      text-align: center;
      background-color: black;
      color: white;
      cursor: pointer;
      border: 5px solid gray;
      box-sizing: border-box;
    }
    
    .horizontal-slider .example-thumb {
      top: 1px;
      width: 50px;
      height: 48px;
      line-height: 38px;
    }
    
    .horizontal-slider .example-track {
      top: 20px;
      height: 10px;
    }
    .example-track {
      background: rgb(221, 221, 221);
    }
    
    .example-track.example-track-1 {
      background: rgb(255, 0, 0);
    }
    
    .example-track.example-track-2 {
      background: rgb(0, 255, 0);
    }
    import React from "react";
    import ReactSlider from "react-slider";
    
    import "./styles.css";
    
    function App() {
      return (
        <div>
          <ReactSlider
            className="horizontal-slider"
            thumbClassName="example-thumb"
            trackClassName="example-track"
            defaultValue={[0, 50, 100]}
            ariaLabel={["Leftmost thumb", "Middle thumb", "Rightmost thumb"]}
            renderThumb={(props, state) => <div {...props}>{state.valueNow}</div>}
            pearling
            minDistance={10}
          />
        </div>
      );
    }
    
    export default App;
    A multi slider with three thumbs
  • Vertical slider

    // styles.css
    
    * {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }
    
    body {
      font-family: "Roboto", sans-serif;
    }
    
    .vertical-slider {
      height: 380px;
      width: 50px;
      border: 1px solid grey;
    }
    
    .example-thumb {
      font-size: 0.9em;
      text-align: center;
      background-color: black;
      color: white;
      cursor: pointer;
      border: 5px solid gray;
      box-sizing: border-box;
    }
    
    .vertical-slider .example-thumb {
      left: 1px;
      width: 48px;
      line-height: 40px;
      height: 50px;
    }
    
    .vertical-slider .example-track {
      left: 20px;
      width: 10px;
    }
    
    .example-track {
      background: rgb(221, 221, 221);
    }
    
    .example-track.example-track-1 {
      background: rgb(255, 0, 0);
    }
    
    .example-track.example-track-2 {
      background: rgb(0, 255, 0);
    }
    import React from "react";
    import ReactSlider from "react-slider";
    
    import "./styles.css";
    
    function App() {
      return (
        <div>
          <ReactSlider
            className="vertical-slider"
            thumbClassName="example-thumb"
            trackClassName="example-track"
            defaultValue={[0, 50, 100]}
            ariaLabel={["Lowest thumb", "Middle thumb", "Top thumb"]}
            renderThumb={(props, state) => <div {...props}>{state.valueNow}</div>}
            orientation="vertical"
            invert
            pearling
            minDistance={10}
          />
        </div>
      );
    }
    
    export default App;
    A vertical slider with three thumbs

To learn more about the `react-slider` library, check out the tutorial video below:

Employing rc-slider

The `rc-slider` library provides a slider UI component for building custom range sliders in a React application. It is lightweight, accessible, and works well for various browsers and screen dimensions. The `rc-slider` library supports props that help developers customize the slider in a way that enhances user interaction, including:

  • handleStyle: This prop is used to apply styles to the handle.

  • trackStyle: This prop sets the style used for the track.

  • railStyle: This styles the track base color.

  • dotStyle: This prop applies the style used for the dot.

  • activeDotStyle: This prop styles the active dots.

Consider the following for building a custom slider with `rc-slider`:

// styles.css

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

body {
  font-family: "Roboto", sans-serif;
  height: 100vh;
  padding: 0 1rem;
}

.app > div {
  padding: 1rem 0;
}

label {
  margin-bottom: 0.5rem;
  display: inline-block;
}
import React, { useState } from "react";
import Slider from "rc-slider";
import "rc-slider/assets/index.css";
import "./styles.css";

function ControlledRange() {
  const [rangeState, setRangeState] = useState([20, 40, 60, 80]);

  const handleChange = (value) => {
    setRangeState(value);
  };

  return <Slider range value={rangeState} onChange={handleChange} />;
}

const marks = {
  "-10": "-10°C",
  0: <strong>0°C</strong>,
  26: "26°C",
  37: "37°C",
  50: "50°C",
  100: {
    style: {
      color: "red",
    },
    label: <strong>100°C</strong>,
  },
};

function App() {
  function log(value) {
    console.log(value); //eslint-disable-line
  }

  return (
    <div className="app">
      <div>
        {/* A slider with a step of 20 and default value of 50 */}
        <label>A slider with a step of 20 and default value of 50</label>
        <Slider step={20} defaultValue={50} onChange={log} />
      </div>
      <div>
        {/* Slider with dots */}
        <label>Slider with dots</label>
        <Slider dots step={20} defaultValue={100} onChangeComplete={log} />
      </div>
      <div>
        {/* A slider with a custom track and handle style */}
        <label>A slider with a custom track and handle style</label>
        <Slider
          defaultValue={30}
          trackStyle={{ backgroundColor: "blue", height: 10 }}
          handleStyle={{
            borderColor: "blue",
            height: 28,
            width: 28,
            marginLeft: -14,
            marginTop: -9,
            backgroundColor: "black",
          }}
          railStyle={{ backgroundColor: "red", height: 10 }}
        />
      </div>
      <div>
        {/* A controlled range slider */}
        <label>A controlled range slider</label>
        <ControlledRange />
      </div>
      <div>
        {/* Slider with marks */}
        <label>Slider with marks</label>
        <Slider
          dots
          min={-10}
          marks={marks}
          step={10}
          onChange={log}
          defaultValue={20}
        />
      </div>
    </div>
  );
}

export default App;
Custom sliders implemented with the `rc-slider` library

Leveraging rsuite

The `rsuite` library is a UI library for React that provides various components including a slider element. This library allows developers to create customizable sliders for selecting values within a range. The code below shows how to use it:

// styles.css

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

body {
  font-family: "Roboto", sans-serif;
  padding: 0 1rem;
}

.app {
  height: 100vh;
}

.app > div {
  padding: 1rem 0;
  width: 100%;
}

label {
  display: inline-block;
  margin-bottom: 0.5rem;
}
import React from "react";
import { Slider } from "rsuite";
import "rsuite/dist/rsuite.css";
import "./styles.css";

const App = () => {
  return (
    <div className="app">
      <div>
        <label>A basic progress slider</label>
        <Slider
          progress
          defaultValue={50}
          onChange={(value) => {
            console.log(value);
          }}
        />
      </div>
      <div>
        <label>A graduated slider with marks from 10 to 100</label>
        <Slider
          defaultValue={50}
          min={10}
          step={10}
          max={100}
          graduated
          progress
          renderMark={(mark) => {
            return mark;
          }}
        />
      </div>
      <div style={{ height: "300px" }}>
        <label>A vertical graduated slider</label>
        <Slider
          defaultValue={50}
          min={0}
          step={10}
          max={100}
          graduated
          vertical
          progress
          renderMark={(mark) => {
            return <span>{mark} °C</span>;
          }}
        />
      </div>
    </div>
  );
}

export default App;
Custom sliders implemented with the `rsuite` library

Using the Material UI Slider

Material UI (MUI) also provides a slider element that reflects a range of values from which users can select a single value. The MUI slider supports several customization options to modify the visual aesthetics, behavior, and functionality for optimal user interaction. Below are a few examples:

import React from "react";
import { Box, Slider } from "@mui/material";

function valuetext(value: number) {
  return `${value}°C`;
}

const marks = [
  {
    value: 0,
    label: "0°C",
  },
  {
    value: 20,
    label: "20°C",
  },
  {
    value: 37,
    label: "37°C",
  },
  {
    value: 100,
    label: "100°C",
  },
];

const App = function () {
  return (
    <div className="app">
      <Box>
        <label>A discrete slider</label>
        <Slider
          aria-label="Temperature"
          defaultValue={30}
          getAriaValueText={valuetext}
          valueLabelDisplay="auto"
          shiftStep={30}
          step={10}
          marks
          min={10}
          max={110}
        />
      </Box>
      <Box>
        <label>Custom marks</label>
        <Slider
          aria-label="Custom marks"
          defaultValue={20}
          getAriaValueText={valuetext}
          step={10}
          valueLabelDisplay="auto"
          marks={marks}
        />
      </Box>
      <Box>
        <label>Slider with visible label</label>
        <Slider
          aria-label="Always visible"
          defaultValue={50}
          getAriaValueText={valuetext}
          step={10}
          marks={marks}
          valueLabelDisplay="on"
        />
      </Box>
      <Box>
        <label>Colored slider</label>
        <Slider
          aria-label="Temperature"
          defaultValue={30}
          getAriaValueText={valuetext}
          color="secondary"
        />
      </Box>
    </div>
  );
}

export default App;
Custom sliders implemented with the MUI library

Comparing the different React Slider Libraries

In the preceding section, we discussed the slider customization options different libraries offer. When comparing these libraries, it is vital to consider factors such as features, optimization, and community support. Below is a table with a comparison of the different slider libraries:

react-slider Libraryrc-slider Libraryrsuite LibraryMUI Library
The react-slider library has a minified bundle size of 12kb.The rc-slider library has the lightest bundle size at 8.4kb in the minified version.The rsuite library has a minified bundle size of 191.2kb.Material UI is a popular UI framework with a core that has a minified bundle size of around 300kb.
Being CSS-agnostic is beneficial for flexibility, reusability, and compatibility with different CSS frameworks but offers limited customization options.It offers extensive customization options.It offers fewer customization options.It has limited customization options.
It has less extensive and comprehensive documentation and a smaller community.It has comprehensive documentation and a large community of developers.It has a comprehensive documentation and a sizable community of developers.It has beginner-friendly documentation and is popular among the development community.

Managing Changes to the React Slider

React enables developers to manage changes to the slider value or any associated state in response to user interaction. It provides the `value` and `onChange` props to help keep track of these changes. Changes to the slider element can be handled in the following ways:

  • State management

  • Event handlers

State Management

React state allows us to keep track of the current value of the slider element in response to user interaction. The code below shows how to achieve this:

import ReactSlider from "react-slider";

const App = () => {
  const [sliderValue, setSliderValue] = useState(0);

  const changeHandler = (value) => {
    setSliderValue(value);
  };

  return (
    <div className="app">
      <ReactSlider
        className="horizontal-slider"
        thumbClassName="example-thumb"
        trackClassName="example-track"
        value={sliderValue}
        onChange={changeHandler}
        renderThumb={(props, state) => <div {...props}>{state.valueNow}</div>}
      />
    </div>
  );
}

export default App;

In the given code, the state was introduced to the React functional component to monitor the slider’s current value. Assigning a state variable to the `value` prop without updating the state using the `onChange` prop caused the slider thumb to always snap back to its initial position upon interaction. Nevertheless, when the slider state is appropriately updated with the `onChange` prop, the thumb retains its position as dragged by the user.

Event Handlers

In a previous example, we utilized the `onChange` prop to manage state updates for the slider element. However, libraries like the `react-slider` and `rc-slider` support additional events such as the `onBeforeChange` and `onAfterChange` props, which allows us to perform other actions at the beginning and end of slider interaction. Consider the following:

import ReactSlider from "react-slider";

const App = () => {
  return (
    <div className="app">
      <ReactSlider
        className="horizontal-slider"
        thumbClassName="example-thumb"
        trackClassName="example-track"
        onBeforeChange={() => {
          console.log("Do something before change");
        }}
        onAfterChange={() => {
          console.log("Do something after change");
        }}
        renderThumb={(props, state) => <div {...props}>{state.valueNow}</div>}
      />
    </div>
  );
}

export default App;

Ensuring Accessibility in Your React Slider

It is vital to consider accessibility when integrating a slider into your React application. This approach ensures all users of your application can interact with and navigate the slider element without impeding the user experience. Consider the options below:

  • Employ ARIA attributes: It is essential to use the ARIA (Accessible Rich Internet Application) attributes to enhance the accessibility of slider elements. Ensure to use the`aria-label``aria-labelledby`, and `aria-valuetext` props to provide descriptive labels and instructions for screen reader users.

  • Provide a visual indicator: It is vital to let the user know which value they are selecting. This method guarantees the user is aware of the available options. Ensure the thumb is large enough that the user’s finger or cursor does not obscure the slider value and the `aria-valuenow` prop is applied to indicate the current value to assistive technology.

  • Ensure keyboard navigation: Ensure proper navigation and interaction with slider elements using the keyboard controls.

  • Focus management: Providing proper focus when interacting with the sliders is essential. Users should be able to focus on the slider using the tab key.

Benefits of React Slider

Sliders in React offer several merits when building a user interface, including:

  • Interactive user experience

  • Responsiveness and cross-browser support

  • Accessibility

  • Seamless flexibility and customization options

  • Performance optimization

Interactive User experience

Slider components provide an intuitive way for users to select from a specified range. Sliders in React make it easy to display a visual cue as users drag the handle across the track to the desired value, enhancing the user experience.

Responsiveness and Cross-browser Support

The React libraries discussed in a previous section provide a slider component that can adjust its dimension and has support on different devices and platforms. The `rc-slider` provides touch support and can be easily integrated into mobile and touch-screen devices.

Accessibility

Several React slider libraries include built-in accessibility features, providing keyboard navigation and screen reader support. This feature improves the user experience by ensuring inclusivity for all the application users.

Seamless Flexibility and Customization Options

The React slider libraries provide several props that allow developers to customize the slider’s appearance, behavior, and functionality. This merit ensures the effective implementation of slider elements to match the application requirements and design aesthetics.

Performance Optimization

Several React slider libraries are lightweight with small bundle sizes for efficient performance. These sliders can handle large datasets with smooth user interaction, providing a seamless user experience.

Final Thoughts

As a frequently used UI element, sliders transcend their fundamental function as range input fields to offer users control over application behavior. While several libraries and frameworks provide a slider element for user interfaces, the `rc-slider` stands out for its flexibility, extensive customization options, and lightweight bundle size. These factors are vital in improving the user experience during slider interaction. Therefore, selecting the right slider is crucial in enhancing the visual aesthetic and user engagement.

Finally, explore how Purecode AI, an AI-powered code automation platform can improve your development workflow by generating customizable UI components to meet your React project requirements.

Recommended Reading

If you enjoyed this article, consider reading other articles from our blog to boost your React knowledge:

Ofili Chukwuemeka Timothy

Ofili Chukwuemeka Timothy