Radix homepage
Components

Switch

A control that allows the user to toggle between checked and not checked.

import React from 'react';
import { styled } from '@stitches/react';
import { violet, mauve, blackA, whiteA } from '@radix-ui/colors';
import * as SwitchPrimitive from '@radix-ui/react-switch';
const StyledSwitch = styled(SwitchPrimitive.Root, {
all: 'unset',
width: 42,
height: 25,
backgroundColor: blackA.blackA9,
borderRadius: '9999px',
position: 'relative',
boxShadow: `0 2px 10px ${blackA.blackA7}`,
WebkitTapHighlightColor: 'rgba(0, 0, 0, 0)',
'&:focus': { boxShadow: `0 0 0 2px black` },
'&[data-state="checked"]': { backgroundColor: 'black' },
});
const StyledThumb = styled(SwitchPrimitive.Thumb, {
display: 'block',
width: 21,
height: 21,
backgroundColor: 'white',
borderRadius: '9999px',
boxShadow: `0 2px 2px ${blackA.blackA7}`,
transition: 'transform 100ms',
transform: 'translateX(2px)',
willChange: 'transform',
'&[data-state="checked"]': { transform: 'translateX(19px)' },
});
// Exports
export const Switch = StyledSwitch;
export const SwitchThumb = StyledThumb;
// Your app...
const Flex = styled('div', { display: 'flex' });
const Label = styled('label', {
color: 'white',
fontSize: 15,
lineHeight: 1,
userSelect: 'none',
});
const SwitchDemo = () => (
<form>
<Flex css={{ alignItems: 'center' }}>
<Label htmlFor="s1" css={{ paddingRight: 15 }}>
Airplane mode
</Label>
<Switch defaultChecked id="s1">
<SwitchThumb />
</Switch>
</Flex>
</form>
);
export default SwitchDemo;

Features

  • Full keyboard navigation.
  • Can be controlled or uncontrolled.

Install the component from your command line.

npm install @radix-ui/react-switch

Import all parts and piece them together.

import * as Switch from '@radix-ui/react-switch';
export default () => (
<Switch.Root>
<Switch.Thumb />
</Switch.Root>
);

Contains all the parts of a switch. An input will also render when used within a form to ensure events propagate correctly.

PropTypeDefault
asChildbooleanfalse
defaultCheckedbooleanNo default value
checkedbooleanNo default value
onCheckedChangefunctionNo default value
disabledbooleanNo default value
requiredbooleanNo default value
namestringNo default value
valuestringon
Data AttributeValues
[data-state]"checked" | "unchecked"
[data-disabled]Present when disabled

The thumb that is used to visually indicate whether the switch is on or off.

PropTypeDefault
asChildbooleanfalse
Data AttributeValues
[data-state]"checked" | "unchecked"
[data-disabled]Present when disabled

Adheres to the switch role requirements.

KeyDescription
SpaceToggles the component's state.
EnterToggles the component's state.