Switch
Capture boolean input from user
Import
Source
Docs
Package
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.
Size
Radius
Color
<Switchlabel="I agree to sell my privacy"/>
Sizes
Switch has 5 predefined sizes: xs, sm, md, lg, xl. Size defines label font-size (from theme.fontSizes), 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 number to set radius in px:
<Switch radius="lg" /> // -> theme predefined large radius<Switch radius={10} /> // -> { borderRadius: 10 }
Controlled
import React, { 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 React, { useRef } from 'react';import { Switch } from '@mantine/core';function Demo() {const ref = useRef();return <Switch elementRef={ref} />;}
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