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;
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.
Prop | Type | Default |
---|---|---|
asChild | boolean | false |
defaultChecked | boolean | |
checked | boolean | |
onCheckedChange | function | |
disabled | boolean | |
required | boolean | |
name | string | |
value | string | on |
The thumb that is used to visually indicate whether the switch is on or off.
Prop | Type | Default |
---|---|---|
asChild | boolean | false |
Adheres to the switch
role requirements.
Key | Description |
---|---|
Space | Toggles the component's state. |
Enter | Toggles the component's state. |