How to disable clicking the track to change value in material ui slider?

Viewed 1004

The need arises when there are multiple thumbs in a slider. In such a scenario, it is not known which thumb the user intends to move by clicking the track.

Solution:

When multiple thumbs are present, the values can only be controlled by moving the thumb:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles, makeStyles } from '@material-ui/core/styles';
import Slider from '@material-ui/core/Slider';
import Typography from '@material-ui/core/Typography';
import Tooltip from '@material-ui/core/Tooltip';

const useStyles = makeStyles((theme) => ({
  root: {
    width: 300 + theme.spacing(3) * 2,
  },
  margin: {
    height: theme.spacing(3),
  },
}));

const AirbnbSlider = withStyles({
  root: {
    color: '#3a8589',
    height: 3,
    padding: '13px 0',
  },
  thumb: {
    height: 27,
    width: 27,
    backgroundColor: '#fff',
    border: '1px solid currentColor',
    marginTop: -12,
    marginLeft: -13,
    boxShadow: '#ebebeb 0 2px 2px',
    '&:focus, &:hover, &$active': {
      boxShadow: '#ccc 0 2px 3px 1px',
    },
    '& .bar': {
      // display: inline-block !important;
      height: 9,
      width: 1,
      backgroundColor: 'currentColor',
      marginLeft: 1,
      marginRight: 1,
    },
  },
  active: {},
  track: {
    height: 3,
  },
  rail: {
    color: '#d8d8d8',
    opacity: 1,
    height: 3,
  },
})(Slider);

function AirbnbThumbComponent(props) {
  return (
    <span {...props}>
      <span className="bar" />
      <span className="bar" />
      <span className="bar" />
    </span>
  );
}

enter image description here

1 Answers

I was facing the same issue and stumbled onto this question. I am using styled components to create overridden styles on the Slider component. You can also do this by the classes attribute provided internally by Material UI. I was able to solve it by doing two things:

  1. Set pointer-events: none !important on the class MuiSlider-root.
  2. Set pointer-events: all !important on the class MuiSlider-thumb.

You can check out a working solution here: https://codesandbox.io/s/busy-mcclintock-1hw1x?file=/src/MultiRangeSlider.jsx:366-381

Related