Switch

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

Features

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

Install the component from your command line.

npm install @radix-ui/react-switch

Import the components and piece the parts together.

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

Create your styled switch component from the primitive parts.

import { styled } from 'path-to/stitches.config';
import * as Switch from '@radix-ui/react-switch';
const StyledSwitch = styled(Switch.Root, {
appearance: 'none',
backgroundColor: 'transparent',
border: 'none',
padding: 0,
width: 25,
height: 15,
backgroundColor: 'gainsboro',
borderRadius: 25,
position: 'relative',
'&:focus': {
outline: 'none',
boxShadow: '0 0 0 2px royalblue',
},
'&[data-state="checked"]': {
backgroundColor: 'dodgerblue',
},
});
const StyledThumb = styled(Switch.Thumb, {
display: 'block',
width: 13,
height: 13,
backgroundColor: 'white',
borderRadius: '$round',
boxShadow: 'rgba(0, 0, 0, 0.3) 0px 0px 2px',
transition: 'transform 100ms',
transform: 'translateX(1px)',
willChange: 'transform',
'&[data-state="checked"]': {
transform: 'translateX(11px)',
},
});
export default () => (
<StyledSwitch>
<StyledThumb />
</StyledSwitch>
);

Contains all the parts of a switch.

PropTypeDefault
asenumbutton
defaultCheckedbooleanNo default value
checkedbooleanNo default value
onCheckedChangefunctionNo default value
disabledbooleanNo default value
requiredbooleanNo default value
namestringNo default value
valuestringon

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

PropTypeDefault
asenumspan

Adheres to the switch role requirements.

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