Juara
Juara

Reputation: 97

Customizing styles on Slider Material-UI (React)

I'm trying to make a slider with restricted values with Material UI and React. I have copy the basic implementation from the documentation page and it seem's not to need CSS to function. But when I use it in my project, the labels appear overlapped as the color of the line representing the chosen value (with 0 value, the line is light blue, with 5 value, all the line is heavy blue).

This is the code I have implemented:

const useStyles = makeStyles({


root: {
    width: 300,
  },
  
});

const marks = [
  {
    value: 1,
    label: 'Nada',
  },
  {
    value: 2,
    label: 'Un poco',
  },
  {
    value: 3,
    label: 'Moderado',
  },
  {
    value: 4,
    label: 'Bastante',
  },
  {
      value: 5,
      label: 'Totalmente'
  }
];

function valuetext(value) {
  return `${value}`;
}

function valueLabelFormat(value) {
  return marks.findIndex((mark) => mark.value === value) + 1;
}

export default function DiscreteSlider() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Typography id="discrete-slider-restrict" gutterBottom>
        Restricted values
      </Typography>
      <Slider
        defaultValue={0}
        valueLabelFormat={valueLabelFormat}
        getAriaValueText={valuetext}
        aria-labelledby="discrete-slider-restrict"
        step={null}
        valueLabelDisplay="auto"
        marks={marks}
      />
    </div>
  );
}

And the Slider looks like that: Slider

How can I change the overlapping and make it functional? Is there any Slider prop that I can use?

Thank you very much!

Upvotes: 2

Views: 5468

Answers (1)

95faf8e76605e973
95faf8e76605e973

Reputation: 14191

Set max for the Slider to 5 - currently it is defaulting to 100 (see docs for default value). Currently, your mark values are 1 to 5 so they are being squeezed in that tiny area

<Slider
  max={5}  // <-- set max
  defaultValue={0}
  valueLabelFormat={valueLabelFormat}
  getAriaValueText={valuetext}
  aria-labelledby="discrete-slider-restrict"
  step={null}
  valueLabelDisplay="auto"
  marks={marks}
/>

and allocate more width to accomodate the labels

const useStyles = makeStyles({
  root: {
    width: 600
  }
});

Upvotes: 2

Related Questions