Glrk UI

Toggle Group

A simplified wrapper for Shadcn Toggle Group with flexible option handling and automatic type conversion

Installation

npx shadcn@latest add @glrk-ui/toggle-group

If you haven't set up the prerequisites yet, check out Prerequest section.

Copy and paste the following code into shadcn toggle-group component.

import { cn, getKey, getLabel, getValue, isOption } from "@/lib/utils"
ui/toggle-group.tsx
type toggleItemT = allowedPrimitiveT | (optionT & {
  "aria-label"?: string
})

type toggleItemsT = toggleItemT[]

type itemProps = {
  option: toggleItemT
  className?: string
}

function Item({ option, className }: itemProps) {
  const value = getValue(option)
  const label = getLabel(option)
  const isObj = isOption(option)

  return (
    <ToggleGroupItem
      value={`${value}`}
      className={cn(className, isObj && option.className)}
      aria-label={isObj ? option["aria-label"] : undefined}
    >
      {isObj ? label : `${label}`}
    </ToggleGroupItem>
  )
}

type props = {
  options: toggleItemT[]
  itemCls?: string
  type?: "single" | "multiple"
} & Omit<React.ComponentProps<typeof ToggleGroupPrimitive.Root>, "type">

function ToggleGroupWrapper({
  options,
  itemCls,
  type = "single",
  ...props
}: props) {
  return (
    <ToggleGroup type={type} {...(props as any)}>
      {options.map((option, i) => (
        <Item
          key={getKey(option, i)}
          option={option}
          className={itemCls}
        />
      ))}
    </ToggleGroup>
  )
}

Updated ToggleGroupWrapper in the export block.

export {
  ToggleGroup,
  ToggleGroupItem,
  ToggleGroupWrapper,
  type toggleItemT,
  type toggleItemsT,
}

Installation

npm install @radix-ui/react-toggle @radix-ui/react-toggle-group

toggle-group.tsx

Copy and paste the following code into your project.

ui/toggle.tsx
"use client"

import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "@/lib/utils"

const toggleVariants = cva(
  "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
  {
    variants: {
      variant: {
        default: "bg-transparent",
        outline:
          "border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
      },
      size: {
        default: "h-9 px-2 min-w-9",
        sm: "h-8 px-1.5 min-w-8",
        lg: "h-10 px-2.5 min-w-10",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

function Toggle({
  className,
  variant,
  size,
  ...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
  VariantProps<typeof toggleVariants>) {
  return (
    <TogglePrimitive.Root
      data-slot="toggle"
      className={cn(toggleVariants({ variant, size, className }))}
      {...props}
    />
  )
}

export { Toggle, toggleVariants }
ui/toggle-group.tsx
"use client"

import * as React from "react"
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority"

import { cn, getKey, getLabel, getValue, isOption } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"

const ToggleGroupContext = React.createContext<
  VariantProps<typeof toggleVariants> & {
    spacing?: number
  }
>({
  size: "default",
  variant: "default",
  spacing: 0,
})

function ToggleGroup({
  className,
  variant,
  size,
  spacing = 0,
  children,
  ...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
  VariantProps<typeof toggleVariants> & {
    spacing?: number
  }) {
  return (
    <ToggleGroupPrimitive.Root
      data-slot="toggle-group"
      data-variant={variant}
      data-size={size}
      data-spacing={spacing}
      style={{ "--gap": spacing } as React.CSSProperties}
      className={cn(
        "group/toggle-group flex w-fit items-center gap-[--spacing(var(--gap))] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",
        className
      )}
      {...props}
    >
      <ToggleGroupContext.Provider value={{ variant, size, spacing }}>
        {children}
      </ToggleGroupContext.Provider>
    </ToggleGroupPrimitive.Root>
  )
}

function ToggleGroupItem({
  className,
  children,
  variant,
  size,
  ...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
  VariantProps<typeof toggleVariants>) {
  const context = React.useContext(ToggleGroupContext)

  return (
    <ToggleGroupPrimitive.Item
      data-slot="toggle-group-item"
      data-variant={context.variant || variant}
      data-size={context.size || size}
      data-spacing={context.spacing}
      className={cn(
        toggleVariants({
          variant: context.variant || variant,
          size: context.size || size,
        }),
        "w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10",
        "data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",
        className
      )}
      {...props}
    >
      {children}
    </ToggleGroupPrimitive.Item>
  )
}

type toggleItemT = allowedPrimitiveT | (optionT & {
  "aria-label"?: string
})

type toggleItemsT = toggleItemT[]

type itemProps = {
  option: toggleItemT
  className?: string
}

function Item({ option, className }: itemProps) {
  const value = getValue(option)
  const label = getLabel(option)
  const isObj = isOption(option)

  return (
    <ToggleGroupItem
      value={`${value}`}
      className={cn("border", className, isObj && option.className)}
      aria-label={isObj ? option["aria-label"] : undefined}
    >
      {isObj ? label : `${label}`}
    </ToggleGroupItem>
  )
}

type props = {
  options: toggleItemT[]
  itemCls?: string
  type?: "single" | "multiple"
} & Omit<React.ComponentProps<typeof ToggleGroupPrimitive.Root>, "type">

function ToggleGroupWrapper({
  options,
  itemCls,
  type = "single",
  ...props
}: props) {
  return (
    <ToggleGroup type={type} {...(props as any)}>
      {options.map((option, i) => (
        <Item
          key={getKey(option, i)}
          option={option}
          className={itemCls}
        />
      ))}
    </ToggleGroup>
  )
}

export {
  ToggleGroup,
  ToggleGroupItem,
  ToggleGroupWrapper,
  type toggleItemT,
  type toggleItemsT,
}

Done

You can now use ToggleGroupWrapper

Usage

Basic

import { ToggleGroupWrapper } from "@/components/ui/toggle-group";

export function Basic() {
  return (
     <ToggleGroupWrapper
      options={["Toogle 1", "Toggle 2"]}
    />
  )
}

Reference

ToggleGroupWrapper

Prop

Type