Discord
Source code

ColorSwatch

Display color swatch
Import

Usage

Use ColorSwatch to display color:

<ColorSwatch color="#c3c3c3" />

Example with default Mantine theme colors:

import { ColorSwatch, Group, useMantineTheme } from '@mantine/core';
function Demo() {
const theme = useMantineTheme();
const swatches = Object.keys(theme.colors).map((color) => (
<ColorSwatch key={color} color={theme.colors[color][6]} />
));
return (
<Group position="center" spacing="xs">
{swatches}
</Group>
);
}

Alpha channel

Color swatch has checkers background – you can use it to show transparency in colors:

import { ColorSwatch, Group, useMantineTheme, hexToRgba } from '@mantine/core';
function Demo() {
const theme = useMantineTheme();
const swatches = Object.keys(theme.colors).map((color) => (
<ColorSwatch key={color} color={hexToRgba(theme.colors[color][6], 0.5)} />
));
return (
<Group position="center" spacing="xs">
{swatches}
</Group>
);
}

Size and radius

ColorSwatch does not have predefined size values, use number to set width and height in px, radius has predefined xs, sm, md, lg, xl values from theme.radius:

<ColorSwatch size={50} /> // -> { width: 50, height: 50 }
<ColorSwatch radius="lg" /> // -> theme predefined large radius
<ColorSwatch radius={10} /> // -> { borderRadius: 10 }

Custom component

Use any component or element with ColorSwatch by setting component prop:

import { useState } from 'react';
import { CheckIcon } from '@modulz/radix-icons';
import { ColorSwatch, Group, useMantineTheme } from '@mantine/core';
function Demo() {
const theme = useMantineTheme();
const [checked, setChecked] = useState(true);
return (
<Group position="center" spacing="xs">
<ColorSwatch component="a" href="https://mantine.dev" color={theme.colors.blue[6]} />
<ColorSwatch
component="button"
color={theme.colors.grape[6]}
onClick={() => setChecked((c) => !c)}
style={{ color: '#fff', cursor: 'pointer' }}
>
{checked && <CheckIcon />}
</ColorSwatch>
</Group>
);
}

Get element ref

You can get root element ref with elementRef prop:

import { useRef } from 'react';
import { ColorSwatch } from '@mantine/core';
function Demo() {
const ref = useRef();
return <ColorSwatch elementRef={ref} />;
}

TypeScript

You need to pass additional types to use custom component with TypeScript in case you need full type coverage for events and elementRef:

<ColorSwatch<'button', HTMLButtonElement>
component="button"
onClick={(event) => console.log(event)}
elementRef={(node) => {
window.myRef = node;
}}
/>
<ColorSwatch<typeof Link, HTMLAnchorElement>
component={Link}
onClick={(event) => console.log(event)}
elementRef={(node) => {
window.myRef = node;
}}
/>
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