Switch
Usage
Switch is another variant of Checkbox
component. Use it to capture boolean value input from user.
For better accessibility set label
prop, it will add associated label element.
<Switchlabel="I agree to sell my privacy"/>
Sizes
Switch has 5 predefined sizes: xs, sm, md, lg, xl. Size defines label font-size, input width and height.
You can get switch sizes by importing SWITCH_SIZES
:
import { SWITCH_SIZES } from '@mantine/core';
Prop value | Width | Height |
---|---|---|
xs | 28px | 14px |
sm | 36px | 18px |
md | 42px | 22px |
lg | 54px | 28px |
xl | 66px | 34px |
Radius
Radius controls border-radius of body and handle. xs, sm, md, lg, xl radius values are defined in theme.radius. Alternatively, you can use a number to set radius in px:
<Switch radius="lg" /> // -> theme predefined large radius<Switch radius={10} /> // -> { borderRadius: 10 }
Controlled
import { useState } from 'react';import { Switch } from '@mantine/core';function Demo() {const [checked, setChecked] = useState(false);return <Switch checked={checked} onChange={(event) => setChecked(event.currentTarget.checked)} />;}
Get element ref
You can get input ref with elementRef
prop to:
import { useRef } from 'react';import { Switch } from '@mantine/core';function Demo() {const ref = useRef();return <Switch elementRef={ref} />;}
Server side rendering
Component uses use-id hook to generate unique ids and aria- attributes,
provide static id
prop to prevent props mismatch:
<Switch /> // -> random id generated both on client and server, props mismatch warning<Switch id="my-switch" /> // -> id is static, no mismatches
Accessibility
Switch is a regular input with checkbox type. Provide aria-label
in case you use switch without label for screen reader support:
<Switch label="My switch" />; // -> ok, input and label is connected<Switch />; // not ok, input is not labeled<Switch aria-label="My switch" />; // -> ok, label is not visible but will be announced by screen reader