Published on

How to Style a Range Input Slider in React

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Style a Slider Thumb with Styled Components in React

If you’re working with sliders (<input type='range'>) in React and using styled-components, you might face challenges styling the thumb properly. This article will guide you through the correct way to style the slider thumb in a clean, reusable manner.

The Problem

By default, the slider (<input type='range'>) has a native appearance that varies between browsers. Styling the thumb (::-webkit-slider-thumb, ::-moz-range-thumb) is tricky when using styled-components because it requires pseudo-elements.

The Solution

Here’s the correct way to apply styles to the slider thumb using styled-components in React:

import styled from 'styled-components'

const Slider = styled.input.attrs({
  type: 'range',
})`
  -webkit-appearance: none;
  width: 100%;
  height: 6px;
  background: #ddd;
  border-radius: 3px;
  outline: none;
  transition: background 0.3s;

  &:hover {
    background: #ccc;
  }

  &::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 15px;
    height: 15px;
    background: #4caf50;
    border-radius: 50%;
    cursor: pointer;
  }

  &::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #4caf50;
    border-radius: 50%;
    cursor: pointer;
  }
`

const App = () => {
  return <Slider />
}

export default App

Explanation

  • &::-webkit-slider-thumb targets WebKit browsers (Chrome, Safari, Edge).
  • &::-moz-range-thumb targets Firefox.
  • The slider track is styled using background, height, and border-radius.
  • The thumb is given a round shape with border-radius: 50% and a green background.
  • cursor: pointer ensures a proper user experience.

FAQs

1. Why is my thumb styling not applied?

Ensure that -webkit-appearance: none; is set on both the slider and the thumb.

2. How do I style the track?

Use &::-webkit-slider-runnable-track and &::-moz-range-track.

  &::-webkit-slider-runnable-track {
    background: #ddd;
    height: 6px;
  }
  &::-moz-range-track {
    background: #ddd;
    height: 6px;
  }

3. How to add a custom image to the thumb?

  &::-webkit-slider-thumb {
    background: url('/path/to/image.png') no-repeat center;
    background-size: cover;
  }