import { Switch } from "@chakra-ui/react" const Demo = () => { return ( <Switch.Root> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label>Activate Chakra</Switch.Label> </Switch.Root> ) }
Usage
import { Switch } from "@chakra-ui/react"
<Switch.Root> <Switch.HiddenInput /> <Switch.Control> <Switch.Thumb /> </Switch.Control> <Switch.Label /> </Switch.Root>
Shortcuts
The Switch
component also provides a set of shortcuts for common use cases.
SwitchControl
The Switch.Control
renders the Switch.Thumb
within it by default.
This works:
<Switch.Control> <Switch.Thumb /> </Switch.Control>
This might be more concise, if you don't need to customize the thumb:
<Switch.Control />
Examples
Sizes
Pass the size
prop to the Switch.Root
component to change the size of the switch component.
import { For, HStack, Switch } from "@chakra-ui/react" const Demo = () => { return ( <HStack gap="8"> <For each={["xs", "sm", "md", "lg"]}> {(size) => ( <Switch.Root key={size} size={size}> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label /> </Switch.Root> )} </For> </HStack> ) }
Variants
Pass the variant
prop to the Switch.Root
component to change the visual style of the switch.
import { For, HStack, Switch } from "@chakra-ui/react" const Demo = () => { return ( <HStack gap="8"> <For each={["raised", "solid"]}> {(variant) => ( <Switch.Root key={variant} variant={variant}> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label /> </Switch.Root> )} </For> </HStack> ) }
Colors
Pass the colorPalette
prop to the Switch.Root
component to change the color scheme of the component.
gray
red
green
blue
teal
pink
purple
cyan
orange
yellow
import { Stack, Switch, Text } from "@chakra-ui/react" import { colorPalettes } from "compositions/lib/color-palettes" const Demo = () => { return ( <Stack gap="2" align="flex-start"> {colorPalettes.map((colorPalette) => ( <Stack align="center" key={colorPalette} direction="row" gap="10" px="4" > <Text minW="8ch">{colorPalette}</Text> <Switch.Root colorPalette={colorPalette}> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label /> </Switch.Root> <Switch.Root colorPalette={colorPalette} defaultChecked> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label /> </Switch.Root> </Stack> ))} </Stack> ) }
Controlled
Use the checked
and onCheckedChange
prop to control the state of the switch.
"use client" import { Switch } from "@chakra-ui/react" import { useState } from "react" const Demo = () => { const [checked, setChecked] = useState(false) return ( <Switch.Root checked={checked} onCheckedChange={(e) => setChecked(e.checked)} > <Switch.HiddenInput /> <Switch.Control> <Switch.Thumb /> </Switch.Control> <Switch.Label /> </Switch.Root> ) }
Hook Form
Here's an example of integrating the switch with react-hook-form
.
"use client" import { Button, Field, Stack, Switch } from "@chakra-ui/react" import { zodResolver } from "@hookform/resolvers/zod" import { Controller, useForm } from "react-hook-form" import { z } from "zod" const formSchema = z.object({ active: z.boolean({ message: "Active is required" }), }) type FormData = z.infer<typeof formSchema> const Demo = () => { const { handleSubmit, control, formState: { errors }, } = useForm<FormData>({ resolver: zodResolver(formSchema), }) return ( <form onSubmit={handleSubmit((data) => console.log(data))}> <Stack align="flex-start"> <Controller name="active" control={control} render={({ field }) => ( <Field.Root invalid={!!errors.active}> <Switch.Root name={field.name} checked={field.value} onCheckedChange={({ checked }) => field.onChange(checked)} > <Switch.HiddenInput onBlur={field.onBlur} /> <Switch.Control /> <Switch.Label>Activate Chakra</Switch.Label> </Switch.Root> <Field.ErrorText>{errors.active?.message}</Field.ErrorText> </Field.Root> )} /> <Button size="sm" type="submit" mt="4"> Submit </Button> </Stack> </form> ) }
Disabled
Pass the disabled
prop to the Switch.Root
component to disable the switch.
import { Switch } from "@chakra-ui/react" const Demo = () => { return ( <Switch.Root disabled> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label>Activate Chakra</Switch.Label> </Switch.Root> ) }
Invalid
Pass the invalid
prop to the Switch.Root
component to indicate an error state for the switch.
import { Switch } from "@chakra-ui/react" const Demo = () => { return ( <Switch.Root invalid> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label>Activate Chakra</Switch.Label> </Switch.Root> ) }
Tooltip
Here's an example of how to compose a switch with a tooltip.
import { Switch } from "@chakra-ui/react" import { Tooltip } from "@/components/ui/tooltip" import { useId } from "react" const Demo = () => { const id = useId() return ( <Tooltip ids={{ trigger: id }} content="This is a tooltip"> <Switch.Root ids={{ root: id }}> <Switch.HiddenInput /> <Switch.Control /> <Switch.Label>Switch with tooltip</Switch.Label> </Switch.Root> </Tooltip> ) }
Track Indicator
Use the Switch.Indicator
component to display different indicators based on the checked state.
"use client" import { Icon, Switch } from "@chakra-ui/react" import { FaMoon, FaSun } from "react-icons/fa" const Demo = () => { return ( <Switch.Root colorPalette="blue" size="lg"> <Switch.HiddenInput /> <Switch.Control> <Switch.Thumb /> <Switch.Indicator fallback={<Icon as={FaMoon} color="gray.400" />}> <Icon as={FaSun} color="yellow.400" /> </Switch.Indicator> </Switch.Control> <Switch.Label>Switch me</Switch.Label> </Switch.Root> ) }
Thumb Indicator
Use the Switch.ThumbIndicator
component to add an icon to the switch thumb.
import { Switch } from "@chakra-ui/react" import { HiCheck, HiX } from "react-icons/hi" const Demo = () => { return ( <Switch.Root size="lg"> <Switch.HiddenInput /> <Switch.Control> <Switch.Thumb> <Switch.ThumbIndicator fallback={<HiX color="black" />}> <HiCheck /> </Switch.ThumbIndicator> </Switch.Thumb> </Switch.Control> <Switch.Label>Switch me</Switch.Label> </Switch.Root> ) }
Closed Component
Here's how to setup the Switch for a closed component composition.
import { Switch as ChakraSwitch } from "@chakra-ui/react" import * as React from "react" export interface SwitchProps extends ChakraSwitch.RootProps { inputProps?: React.InputHTMLAttributes<HTMLInputElement> rootRef?: React.RefObject<HTMLLabelElement | null> trackLabel?: { on: React.ReactNode; off: React.ReactNode } thumbLabel?: { on: React.ReactNode; off: React.ReactNode } } export const Switch = React.forwardRef<HTMLInputElement, SwitchProps>( function Switch(props, ref) { const { inputProps, children, rootRef, trackLabel, thumbLabel, ...rest } = props return ( <ChakraSwitch.Root ref={rootRef} {...rest}> <ChakraSwitch.HiddenInput ref={ref} {...inputProps} /> <ChakraSwitch.Control> <ChakraSwitch.Thumb> {thumbLabel && ( <ChakraSwitch.ThumbIndicator fallback={thumbLabel?.off}> {thumbLabel?.on} </ChakraSwitch.ThumbIndicator> )} </ChakraSwitch.Thumb> {trackLabel && ( <ChakraSwitch.Indicator fallback={trackLabel.off}> {trackLabel.on} </ChakraSwitch.Indicator> )} </ChakraSwitch.Control> {children != null && ( <ChakraSwitch.Label>{children}</ChakraSwitch.Label> )} </ChakraSwitch.Root> ) }, )
If you want to automatically add the closed component to your project, run the command:
npx @chakra-ui/cli snippet add switch
Here's how to use the it
<Switch>Activate Chakra</Switch>
Props
Root
Prop | Default | Type |
---|---|---|
value | '\'on\'' | string | number The value of switch input. Useful for form submission. |
colorPalette | 'gray' | 'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' The color palette of the component |
variant | 'solid' | 'solid' | 'raised' The variant of the component |
size | 'md' | 'xs' | 'sm' | 'md' | 'lg' The size of the component |
as | React.ElementType The underlying element to render. | |
asChild | boolean Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. | |
unstyled | boolean Whether to remove the component's style. | |
checked | boolean The controlled checked state of the switch | |
disabled | boolean Whether the switch is disabled. | |
ids | Partial<{ root: string; hiddenInput: string; control: string; label: string; thumb: string }> The ids of the elements in the switch. Useful for composition. | |
invalid | boolean If `true`, the switch is marked as invalid. | |
label | string Specifies the localized strings that identifies the accessibility elements and their states | |
name | string The name of the input field in a switch (Useful for form submission). | |
onCheckedChange | (details: CheckedChangeDetails) => void Function to call when the switch is clicked. | |
readOnly | boolean Whether the switch is read-only | |
required | boolean If `true`, the switch input is marked as required, |
Explorer
Explore the Switch
component parts interactively. Click on parts in the sidebar to highlight them in the preview.
Component Anatomy
Hover to highlight, click to select parts
root
label
control
thumb
indicator
switch.recipe.ts