Easily Create a Material-UI Image Slider

Material-UI has an extremely robust and customizable slider component. Naturally, I want to push it even farther.

Jon Middaugh
The Clever Dev
3 min readMar 11, 2021

--

Photo by Adi Goldstein on Unsplash

In this demo, I’ll create slider thumbs that have images and set slider behavior based on slider position.

Slider Image Thumbs

There are two methods for creating slider thumbs with an image as the background: CSS or Component.

The CSS version:

First, this actually needs to use thumb class. This is a specific class designated in the Slider API for styling the thumb. Second, it’s actually pretty simple to create an image thumb. Simply set the backgroundImage to a url or file. In this case I used Lorem Picsum, which randomly pulls images from Unsplash.

The Component version:

This method creates a component and passes it to the ThumbComponent prop of the Slider.

I prefer the CSS method because with the component, I still need to style the thumb. However, the component method could be used to insert a component constructed from HTML building blocks, and could result in some pretty cool thumbs.

Related: Test your JavaScript knowledge with these 50 difficult JavaScript questions!

Custom Slider Behavior

Let’s say I want this slider to change to red if the thumbs are more than 50 ticks apart:

First, we need to make sure two thumbs are on the slider. This is achieved simply by setting an array containing two default values:

Next, let’s add an onChange prop and handler.

Notice how I included a ref in the component. Then I pass this ref as a prop to the change handler.

The handler also accepts coordinates, which is simply an array containing the tick position of the two thumbs. The larger value always comes second.

With a bit of math and a logical operator, we can quickly set styling when the thumbs are 50 ticks apart. Using a query selector and exploring the DOM to understand what classes Material-UI applied to the Slider, we can style the ‘track’ (the line between the two thumbs.

If you wanted to create the appearance of an ‘inverted’ track, simply target the MuiSlider-rail class instead. This will color the ‘rail’, which appears to the left of the lesser thumb and to the right of the greater thumb.

There are many out-of-the-box customizations that can be applied to the slider, such as vertical orientation, visible tick marks, segments, and labels. Take a look at the MUI doc links in the Resources section, chances are high the MUI team has already built what you are looking for in the Slider.

Resources

Codesandbox:

Customized Sliders Documentation:

API Documentation:

--

--

Jon Middaugh
The Clever Dev

I have been: individual contributor | tech lead | manager | JS boot camp teacher | community college instructor.