Slider

A slider is an input control for selecting a value from a range of values. You can give colors to the track and thumb.Also, you can select container as square or rounded.

Preview


"use client";
import { Slider } from "@/components/Slider";
import React from "react";

const page = () => {
  return (
    <Slider
      defaultValue={[33]}
      max={100}
      step={1}
      width="w-96"
      trackcolor="bg-black"
      thumbcolor="bg-gray-400"
      container="square"
    />
  );
};

export default page;

Examples

Slider with square container

Slider with rounded container

Install the following dependencies:

npm install @radix-ui/react-slider

Copy and paste the following code into your project.

"use client";

import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import { cn } from "@/lib/utils";
import { VariantProps, cva } from "class-variance-authority";

const sliderVariants = cva("", {
  variants: {
    container: {
      square: "rounded-none",
      rounded: "rounded-full",
    },
  },
  defaultVariants: {
    container: "rounded",
  },
});

interface SliderProps
  extends React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>,
    VariantProps<typeof sliderVariants> {
  trackcolor?: string;
  thumbcolor?: string;
  width?: string;
}

const Slider = React.forwardRef<
  React.ElementRef<typeof SliderPrimitive.Root>,
  SliderProps
>(
  (
    {
      container,
      trackcolor = "bg-black",
      thumbcolor = "bg-white",
      width = `w-80`,
      className,
      ...props
    },
    ref
  ) => (
    <SliderPrimitive.Root
      ref={ref}
      className={cn(
        `relative flex ${width} touch-none select-none items-center`,
        className
      )}
      {...props}
    >
      <SliderPrimitive.Track
        className={`relative h-2 ${width} grow overflow-hidden ${sliderVariants(
          { container }
        )} ${trackcolor}`}
      >
        <SliderPrimitive.Range className="absolute h-full border-transparent bg-gray-300" />
      </SliderPrimitive.Track>
      <SliderPrimitive.Thumb
        className={`block h-5 w-5 ${thumbcolor} rounded-full border-2 border-transparent ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`}
      />
    </SliderPrimitive.Root>
  )
);
Slider.displayName = SliderPrimitive.Root.displayName;

export { Slider };