Discord
Source code

Switch

Capture boolean input from user
Import

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
<Switch
label="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 valueWidthHeight
xs28px14px
sm36px18px
md42px22px
lg54px28px
xl66px34px

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
Build fully functional accessible web applications with ease
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback