ari-m/mantine-rules icon
public
Published on 6/2/2025
Mantine UI LLMs txt

https://context7.com/mantinedev/mantine https://context7.com/mantinedev/mantine/llms.txt?tokens=234561

Rules

TITLE: Checkbox Accessibility Examples (React) DESCRIPTION: These examples demonstrate how to properly label a Checkbox component for accessibility. The Bad example shows an unlabeled checkbox, while GoodAriaLabel and GoodLabel demonstrate labeling using aria-label and the label prop, respectively. Proper labeling is crucial for users with assistive technologies. Requires import of Checkbox from @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/checkbox.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { Checkbox } from '@mantine/core';

// Not ok, input is not labeled
function Bad() {
  return <Checkbox />;
}

// Ok, input is labelled by aria-label
function GoodAriaLabel() {
  return <Checkbox aria-label="My checkbox" />;
}

// Ok, input is labelled by label element
function GoodLabel() {
  return <Checkbox label="My checkbox" />;
}

TITLE: Controlled Select Component with string DESCRIPTION: This example demonstrates a controlled Select component in React, where the value is managed by a state variable. The onChange function is used to update the state when a new option is selected. Value must be a string. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/select.mdx#_snippet_0

LANGUAGE: typescript CODE:

import { useState } from 'react';
import { Select } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState<string | null>('');
  return <Select data={[]} value={value} onChange={setValue} />;
}

TITLE: Creating Throttled Callback Handlers with Mantine and useThrottledCallback (TSX) DESCRIPTION: Illustrates using useThrottledCallback from @mantine/hooks to throttle callback invocations in an input handler. The demonstration sets up a TextInput and displays the latest throttled value, ensuring the setter is called at most once per 1000ms regardless of user typing speed. Necessary dependencies are @mantine/core, @mantine/hooks, and React. No asynchronous work or side effects beyond state mutation. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.8.0.md#_snippet_12

LANGUAGE: tsx CODE:

import { Text, TextInput } from '@mantine/core';
import { useThrottledCallback } from '@mantine/hooks';

function Demo() {
  const [throttledValue, setValue] = useState('');
  const throttledSetValue = useThrottledCallback((value) => setValue(value), 1000);

  return (
    <>
      <TextInput
        placeholder="Search"
        onChange={(event) => throttledSetValue(event.currentTarget.value)}
      />
      <Text>Throttled value: {throttledValue || '–'}</Text>
    </>
  );
}

TITLE: Augmenting Mantine theme types for spacing and radius DESCRIPTION: This TypeScript code demonstrates how to extend the default Mantine theme types for properties like 'spacing' and 'radius' using module augmentation. This allows developers to add custom size values ('xxl', 'xxxs', 'xxs') and have them recognized by the type system. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/8.0.0.md#_snippet_14

LANGUAGE: tsx CODE:

import {
  DefaultMantineSize,
  MantineThemeSizesOverride,
} from '@mantine/core';

type ExtendedCustomSpacing =
  | 'xxl'
  | 'xxxs'
  | DefaultMantineSize;

type ExtendedCustomRadius =
  | 'xxs'
  | DefaultMantineSize;

declare module '@mantine/core' {
  export interface MantineThemeSizesOverride {
    spacing: Record<ExtendedCustomSpacing, string>;
    radius: Record<ExtendedCustomRadius, string>;
  }
}

TITLE: Importing Granular Global Mantine Styles (TypeScript) DESCRIPTION: This snippet shows the updated import paths for Mantine's global styles in version 8.0. It demonstrates how to import baseline.css, default-css-variables.css, and global.css individually for more granular control over styling, replacing previous monolithic imports. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/8-0-0.mdx#_snippet_1

LANGUAGE: tsx CODE:

import '@mantine/core/styles/baseline.css';
import '@mantine/core/styles/default-css-variables.css';
import '@mantine/core/styles/global.css';

TITLE: Avatar Component Accessibility Examples in Mantine DESCRIPTION: This code snippet illustrates how to use the Avatar component with correct and incorrect alt attributes for accessibility. The alt prop is crucial for screen readers and when the image fails to load. The examples show a component without the alt attribute (NotOk), a component with a correct alt (Ok), and a placeholder example using text content with alt attribute (OkPlaceholder). Using alt is necessary for accessibility. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/avatar.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { Avatar } from '@mantine/core';

function NotOk() {
  // Not ok, no alt for image
  return <Avatar src="./image.png" />;
}

function Ok() {
  // Ok, alt is set on <img /> tag
  return <Avatar src="./image.png" alt="Rob Johnson" />;
}

function Ehh() {
  // Ehh, title is not required, but still recommended
  return <Avatar>RJ</Avatar>;
}

function OkPlaceholder() {
  // Ok, title is set on placeholder
  return <Avatar alt="Rob Johnson">RJ</Avatar>;
}

TITLE: Wrapping Application with MantineProvider (TSX) DESCRIPTION: Shows how to wrap the main application component with MantineProvider. This is necessary to provide the Mantine theme and context to all components within the application. An example of creating a basic theme is included. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/getting-started.mdx#_snippet_2

LANGUAGE: TypeScript CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  /** Put your mantine theme override here */
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Mocking Browser APIs for Jest Testing in TSX DESCRIPTION: Provides code for a jest.setup.js file to mock common browser APIs like window.matchMedia, ResizeObserver, window.getComputedStyle, and scrollIntoView. These APIs are required by many Mantine components but are not available in the default jsdom environment, preventing test errors. Requires @testing-library/jest-dom for extended matchers. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/jest.mdx#_snippet_3

LANGUAGE: tsx CODE:

import '@testing-library/jest-dom';

const { getComputedStyle } = window;
window.getComputedStyle = (elt) => getComputedStyle(elt);
window.HTMLElement.prototype.scrollIntoView = () => {};

Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: jest.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: jest.fn(),
    removeListener: jest.fn(),
    addEventListener: jest.fn(),
    removeEventListener: jest.fn(),
    dispatchEvent: jest.fn(),
  })),
});

class ResizeObserver {
  observe() {}
  unobserve() {}
  disconnect() {}
}

window.ResizeObserver = ResizeObserver;

TITLE: Managing Form Values - Mantine (TypeScript/TSX) DESCRIPTION: This snippet collection shows different ways to read and update form values using a useForm instance, supporting both bulk and per-field operations, as well as nested property access. No dependencies are required beyond the initialized useForm instance. Expected inputs are form values or update callbacks, while outputs are updated internal form state objects. These methods are subject to the initial field structure set during initialization. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_1

LANGUAGE: TSX CODE:

// get current form values
form.getValues();

// Set all form values
form.setValues(values);

// Set all form values using the previous state
form.setValues((prev) => ({ ...prev, ...values }));

// Set value of single field
form.setFieldValue('path', value);

// Set value of nested field
form.setFieldValue('user.firstName', 'Jane');

// Resets form values to `initialValues`,
// clears all validation errors,
// resets touched and dirty state
form.reset();

// Sets initial values, used when form is reset
form.setInitialValues({ values: 'object' });

TITLE: Example of Mantine Components in Server Components DESCRIPTION: Highlights that Mantine components use context and cannot be used directly in server components unless using 'use client' or component syntax like 'ComponentXXX'. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/next.mdx#_snippet_9

LANGUAGE: JavaScript CODE:

import { Popover } from '@mantine/core';

// This will throw an error
export default function Page() {
  return (
    <Popover>
      <Popover.Target>Target</Popover.Target>
      <Popover.Dropdown>Dropdown</Popover.Dropdown>
    </Popover>
  );
}

LANGUAGE: JavaScript CODE:

'use client';

import { Popover } from '@mantine/core';

// No error
export default function Page() {
  return (
    <Popover>
      <Popover.Target>Target</Popover.Target>
      <Popover.Dropdown>Dropdown</Popover.Dropdown>
    </Popover>
  );
}

LANGUAGE: JavaScript CODE:

import {
  Popover,
  PopoverDropdown,
  PopoverTarget,
} from '@mantine/core';

// No error
export default function Page() {
  return (
    <Popover>
      <PopoverTarget>Trigger</PopoverTarget>
      <PopoverDropdown>Dropdown</PopoverDropdown>
    </Popover>
  );
}

TITLE: Example of custom component that will not work with Tooltip DESCRIPTION: This example shows code that will not work with Tooltip because the custom component doesn't support the ref prop, which is required for the Tooltip to position correctly relative to the target element. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tooltip.mdx#_snippet_1

LANGUAGE: tsx CODE:

// Example of code that WILL NOT WORK
import { Tooltip } from '@mantine/core';

function MyComponent() {
  return <div>My component</div>;
}

// This will not work – MyComponent does not support ref
function Demo() {
  return (
    <Tooltip label="Does not work">
      <MyComponent />
    </Tooltip>
  );
}

TITLE: Handling onSubmit and onReset Events - Mantine (TypeScript/TSX) DESCRIPTION: This comprehensive example shows how to use form event handlers such as onSubmit and onReset provided by useForm, including handling of validated values and validation errors. It outlines integration with standard React form components and supports both single and dual callback structures for submit handling. Dependencies are @mantine/form and React; input is user event data, and output is typically side effects or log statements. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_5

LANGUAGE: TSX CODE:

import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({ mode: 'uncontrolled' });

  const handleSubmit = (values: typeof form.values) => {
    console.log(values);
  };

  return (
    <>
      {/* Supply handle submit as a single argument to receive validated values */}
      <form onSubmit={form.onSubmit(handleSubmit)} />

      {/* Supply second argument to handle errors */}
      <form
        onSubmit={form.onSubmit(
          (values, event) => {
            console.log(
              values, // <- form.getValues() at the moment of submit
              event // <- form element submit event
            );
          },
          (validationErrors, values, event) => {
            console.log(
              validationErrors, // <- form.errors at the moment of submit
              values, // <- form.getValues() at the moment of submit
              event // <- form element submit event
            );
          }
        )}
      />

      {/* form.onReset calls form.reset */}
      <form onReset={form.onReset}></form>
    </>
  );
}

TITLE: Correct usage with 'use client' directive for callback functions DESCRIPTION: This code shows the proper way to use callback functions as children in Mantine components by including the 'use client' directive at the top of the file, ensuring client-only execution. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_3

LANGUAGE: TypeScript CODE:

// ✅ No error
'use client';

import { CopyButton } from '@mantine/core';

function Demo() {
  return (
    <CopyButton value="https://mantine.dev">
      {({ copied, copy }) => (
        <button color={copied ? 'teal' : 'blue'} onClick={copy}>
          {copied ? 'Copied url' : 'Copy url'}
        </button>
      )}
    </CopyButton>
  );
}

TITLE: Integrating Valibot Schema Types with Mantine Form using TypeScript DESCRIPTION: Explains how to derive the form data type (FormData) from a Valibot schema using v.InferInput. This inferred type is then used as a generic type parameter for the useForm hook (useForm<FormData>), providing strong type safety for initialValues and form handling. Requires mantine-form-valibot-resolver, valibot, and @mantine/form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_15

LANGUAGE: tsx CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver';
import * as v from 'valibot';
import { useForm } from '@mantine/form';

export const userSchema = v.object({
  email: v.pipe(v.string(), v.email()),
});

type FormData = v.InferInput<typeof userSchema>;

const form = useForm<FormData>({
  initialValues: {
    email: '',
  },
  validate: valibotResolver(userSchema),
});

TITLE: Configuring Theme Components for Global Styles (TypeScript) DESCRIPTION: This snippet showcases how to globally control the style and classes of Mantine components by extending their configuration within the createTheme function. Required dependencies: @mantine/core. It demonstrates the inclusion of classNames and styles in the theme, which are subsequently applied project-wide via MantineProvider; expected input includes valid selectors and corresponding class/style values for the component override configuration. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/styles-api.mdx#_snippet_1

LANGUAGE: TypeScript CODE:

const theme = createTheme({
  components: {
    Button: Button.extend({
      classNames: {
        root: 'my-root-class',
        label: 'my-label-class',
        inner: 'my-inner-class',
      },
      styles: {
        root: { backgroundColor: 'red' },
        label: { color: 'blue' },
        inner: { fontSize: 20 },
      },
    }),
  },
});

function ProviderDemo() {
  return (
    <MantineProvider theme={theme}>
      <Button>Button</Button>
    </MantineProvider>
  );
}


TITLE: Validating Basic Fields with Valibot and Mantine Form in TypeScript DESCRIPTION: Demonstrates using valibotResolver with a simple Valibot schema (v.object) containing string (v.string, v.email, v.minLength) and number (v.number, v.minValue) validation rules for basic form fields within useForm. Shows how to define the schema, integrate it into the validate option of useForm, and access validation errors via form.errors after calling form.validate(). Requires mantine-form-valibot-resolver, valibot, and @mantine/form packages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_12

LANGUAGE: tsx CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver';
import * as v from 'valibot';
import { useForm } from '@mantine/form';

const schema = v.object({
  name: v.pipe(
    v.string(),
    v.minLength(2, 'Name should have at least 2 letters')
  ),
  email: v.pipe(v.string(), v.email('Invalid email')),
  age: v.pipe(
    v.number(),
    v.minValue(18, 'You must be at least 18 to create an account')
  ),
});

const form = useForm({
  initialValues: {
    name: '',
    email: '',
    age: 16,
  },
  validate: valibotResolver(schema),
});

form.validate();
form.errors;
// -> {
//  name: 'Name should have at least 2 letters',
//  email: 'Invalid email',
//  age: 'You must be at least 18 to create an account'
// }

TITLE: Configuring Valibot Resolver for Basic Validation DESCRIPTION: This snippet shows how to use valibotResolver to validate form fields using the Valibot library. It defines a schema with validation rules and applies it to a @mantine/form instance. Dependencies include @mantine/form, valibot, and mantine-form-valibot-resolver. The validate method is called, and form.errors will contain the validation errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_14

LANGUAGE: tsx CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver';
import { email, minLength, minValue, number, object, string } from 'valibot';
import { useForm } from '@mantine/form';

const schema = object({
  name: string([minLength(2, 'Name should have at least 2 letters')]),
  email: string([email('Invalid email')]),
  age: number([minValue(18, 'You must be at least 18 to create an account')]),
});

const form = useForm({
  initialValues: {
    name: '',
    email: '',
    age: 16,
  },
  validate: valibotResolver(schema),
});

form.validate();
form.errors;
// -> {
//  name: 'Name should have at least 2 letters',
//  email: 'Invalid email',
//  age: 'You must be at least 18 to create an account'
// }


TITLE: Using React Router Link with Mantine Button (TSX) DESCRIPTION: Shows how to use the component prop of a Mantine Button to render it as a Link component from react-router-dom. This integrates Mantine components with React Router's navigation capabilities. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/polymorphic.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { Link } from 'react-router-dom';
import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button component={Link} to="/react-router">
      React router link
    </Button>
  );
}

TITLE: Setting Default Color Scheme in MantineProvider (TypeScript) DESCRIPTION: Illustrates how to set an initial default color scheme ('dark') for the application when the external storage (like localStorage) does not have a stored value. This ensures a consistent initial appearance. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/mantine-provider.mdx#_snippet_2

LANGUAGE: TypeScript CODE:

import { MantineProvider } from '@mantine/core';

function Demo() {
  return (
    <MantineProvider defaultColorScheme="dark">
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Comparing ColorSchemeScript and MantineProvider defaultColorScheme (TSX) DESCRIPTION: This snippet demonstrates the correct and incorrect ways to use the defaultColorScheme prop with ColorSchemeScript and MantineProvider in a Mantine application. A mismatch in defaultColorScheme values between these two components is highlighted as the primary cause of color scheme flickering (FART) in SSR/SSG setups, while matching values prevent this issue. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/color-scheme-flickering.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { ColorSchemeScript, MantineProvider } from '@mantine/core';

// ❌ Incorrect usage – defaultColorScheme values do not match,
// this will cause color scheme flickering
function IncorrectDemo() {
  return (
    <>
      <ColorSchemeScript defaultColorScheme="light" />
      <MantineProvider defaultColorScheme="auto">
        {/* Your app here */}
      </MantineProvider>
    </>
  );
}

// ✅ Correct usage – defaultColorScheme values match, no FART
function CorrectDemo() {
  return (
    <>
      <ColorSchemeScript defaultColorScheme="light" />
      <MantineProvider defaultColorScheme="light">
        {/* Your app here */}
      </MantineProvider>
    </>
  );
}


TITLE: Using form.initialize to Sync Form with API DESCRIPTION: This code demonstrates the use of form.initialize to sync form values with the response from an API call. It fetches data using apiRequest() and then initializes the form with the fetched data. Dependencies include @mantine/core and @mantine/form. The form.initialize method is called within the onClick handler of a button. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_11

LANGUAGE: tsx CODE:

import { Button, NumberInput, TextInput } from '@mantine/core';
import { isInRange, isNotEmpty, useForm } from '@mantine/form';

interface FormValues {
  name: string;
  age: number | string;
}

function apiRequest(): Promise<FormValues> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ name: 'John Doe', age: 25 });
    }, 1000);
  });
}

function Demo() {
  const form = useForm<FormValues>({
    initialValues: { name: '', age: 0 },
    validate: {
      name: isNotEmpty('Name is required'),
      age: isInRange({ min: 18 }, 'You must be at least 18 to register'),
    },
  });

  return (
    <>
      <TextInput {...form.getInputProps('name')} label="Name" placeholder="Name" />
      <NumberInput {...form.getInputProps('age')} label="Age" placeholder="Age" mt="md" />
      <Button onClick={() => apiRequest().then((values) => form.initialize(values))} mt="md">
        Initialize form
      </Button>
    </>
  );
}


TITLE: Composing Forms with UseFormReturnType Prop - Mantine (TypeScript/TSX) DESCRIPTION: This code sample illustrates passing a strongly-typed useForm instance as a prop to child components, using the UseFormReturnType interface for type safety. This facilitates reusable, isolated input components that participate in a larger form. Required dependencies are @mantine/form, @mantine/core, and React. The input is a form instance, and the output is interconnected, type-safe components reflecting and updating shared form state. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_8

LANGUAGE: TSX CODE:

import { TextInput } from '@mantine/core';
import { useForm, UseFormReturnType } from '@mantine/form';

interface FormValues {
  name: string;
  occupation: string;
}

function NameInput({
  form,
}: {
  form: UseFormReturnType<FormValues>;
}) {
  return (
    <TextInput
      key={form.key('name')}
      {...form.getInputProps('name')}
    />
  );
}

function OccupationInput({
  form,
}: {
  form: UseFormReturnType<FormValues>;
}) {
  return (
    <TextInput
      key={form.key('occupation')}
      {...form.getInputProps('occupation')}
    />
  );
}

function Demo() {
  const form = useForm<FormValues>({
    mode: 'uncontrolled',
    initialValues: { name: '', occupation: '' },
  });
  return (
    <>
      <NameInput form={form} />
      <OccupationInput form={form} />
    </>
  );
}

TITLE: Integrating Mantine Image with Next.js Image (TSX) DESCRIPTION: This snippet demonstrates how to use Mantine's Image component as a wrapper for Next.js's Image component. By setting the component prop to NextImage, you can utilize Mantine's styling props and features while still benefiting from Next.js image optimizations. Requires @mantine/core and next. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/image.mdx#_snippet_0

LANGUAGE: tsx CODE:

import NextImage from 'next/image';
import { Image } from '@mantine/core';
import myImage from './my-image.jpg';

function Demo() {
  return <Image component={NextImage} src={myImage} alt="My image" />;
}

TITLE: Implementing Controlled TextInput Component using Mantine in TypeScript DESCRIPTION: This TypeScript React snippet demonstrates a controlled TextInput component from the Mantine library. It uses the React useState hook to maintain the current input value and updates it on each change event. The snippet requires 'react' for state management and '@mantine/core' for the TextInput component. The input's value is explicitly controlled by the component's local state, ensuring synchronization between the UI and internal state. Inputs are user keystrokes, and outputs are reactive value updates passed as props to the TextInput. This pattern allows custom control over the input's behavior and is essential for validation or related side effects. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/text-input.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { TextInput } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('');
  return (
    <TextInput
      value={value}
      onChange={(event) => setValue(event.currentTarget.value)}
    />
  );
}

TITLE: Exporting Testing Utilities and Custom Render (TSX) DESCRIPTION: This snippet is a testing utilities index file that re-exports all relevant functions from @testing-library/react, the custom render helper, and the userEvent simulation utility. This enables test files to import everything needed for component testing from a single location. Dependencies required: @testing-library/react, ./render (custom helper), @testing-library/user-event. There are no input or output parameters, as this is a utility barrel file. Place it at ./testing-utils/index.ts. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/vitest.mdx#_snippet_4

LANGUAGE: TSX CODE:

import userEvent from '@testing-library/user-event';

export * from '@testing-library/react';
export { render } from './render';
export { userEvent };

TITLE: Implementing Basic Valibot Schema Validation in Mantine Form (TSX) DESCRIPTION: Shows how to integrate Valibot schema validation with @mantine/form using the valibotResolver. Defines a basic schema with string and number validations and applies it to the form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-4-0.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver';
import {
  email,
  minLength,
  minValue,
  number,
  object,
  string,
} from 'valibot';
import { useForm } from '@mantine/form';

const schema = object({
  name: string([minLength(2, 'Name should have at least 2 letters')]),
  email: string([email('Invalid email')]),
  age: number([
    minValue(18, 'You must be at least 18 to create an account'),
  ]),
});

const form = useForm({
  initialValues: {
    name: '',
    email: '',
    age: 16,
  },
  validate: valibotResolver(schema),
});

form.validate();
form.errors;
// -> {
//  name: 'Name should have at least 2 letters',
//  email: 'Invalid email',
//  age: 'You must be at least 18 to create an account'
// }

TITLE: Creating a Controlled Autocomplete Component in React with Mantine DESCRIPTION: This code snippet demonstrates how to implement a controlled Autocomplete component using React's useState hook. It manages the input value and updates it via the onChange handler, ensuring the component's state reflects user input. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/autocomplete.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

import { useState } from 'react';
import { Autocomplete } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('');
  return <Autocomplete data={[]} value={value} onChange={setValue} />;
}

TITLE: Creating Controlled Mantine NativeSelect (TSX) DESCRIPTION: This snippet shows how to control the value of a Mantine NativeSelect component using React's useState hook. It binds the component's value prop to the state variable and updates the state using the onChange handler. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/native-select.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { NativeSelect } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('');

  return (
    <NativeSelect
      value={value}
      onChange={(event) => setValue(event.currentTarget.value)}
      data={['React', 'Angular', 'Svelte', 'Vue']}
    />
  );
}

TITLE: Implementing Controlled ColorInput Component in React with TypeScript DESCRIPTION: This snippet shows how to implement a controlled ColorInput component using React and TypeScript. It demonstrates the use of React's useState hook to manage the color value state and updates the component's value via the onChange callback. The snippet requires @mantine/core library for the ColorInput component and React for state management. The user inputs a color, which updates the local state and the ColorInput's displayed value accordingly. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/color-input.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { ColorInput } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('');
  return <ColorInput value={value} onChange={setValue} />;
}

TITLE: useId with Input and Input.Wrapper DESCRIPTION: Demonstrates how to use the useId hook from @mantine/hooks to generate unique IDs for the Input and Input.Wrapper components. This ensures proper accessibility by connecting the label and input elements correctly. Requires @mantine/core and @mantine/hooks. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/input.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { Input } from '@mantine/core';
import { useId } from '@mantine/hooks';

function Demo() {
  const id = useId();
  return (
    <Input.Wrapper label="Your email" id={id}>
      <Input id={id} />
    </Input.Wrapper>
  );
}

TITLE: Validating nested array list items with Mantine useForm hook in TypeScript DESCRIPTION: Demonstrates validation of list elements within nested array structures using Mantine useForm. The code initializes users as an array of objects with name and age fields, adding validators enforcing minimum name length and adult age requirements. It shows validation of specific fields via validateField and bulk validation with validate(), resulting in a structured errors object keyed by indexed paths like 'users.1.name'. Requires '@mantine/form' and list initialValues input; outputs validation error messages for invalid entries. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/nested.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    users: [
      { name: 'John', age: 12 },
      { name: '', age: 22 },
    ],
  },

  validate: {
    users: {
      name: (value) =>
        value.length < 2
          ? 'Name should have at least 2 letters'
          : null,
      age: (value) =>
        value < 18 ? 'User must be 18 or older' : null,
    },
  },
});

// Validate list item field
form.validateField('users.1.name');

// Or with all other fields
form.validate();
console.log(form.errors);
// {
//  'users.0.age': 'User must be 18 or older',
//  'users.1.name': 'Name should have at least 2 letters'
// }

TITLE: Setting up Mantine Provider in a Vite React Application DESCRIPTION: Example of how to import necessary Mantine styles and wrap your application with MantineProvider in a Vite React project. This setup is essential for Mantine components to work properly with their default styling. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/vite.mdx#_snippet_1

LANGUAGE: tsx CODE:

// Import styles of packages that you've installed.
// All packages except `@mantine/hooks` require styles imports
import '@mantine/core/styles.css';

import { MantineProvider } from '@mantine/core';

export default function App() {
  return <MantineProvider>{/* Your app here */}</MantineProvider>;
}

TITLE: Initializing nested form state with Mantine useForm hook in TypeScript DESCRIPTION: Initializes a form state with nested objects and arrays using Mantine's useForm hook operating in 'uncontrolled' mode. Demonstrates how to access, set, and validate nested fields using string-based property paths. Dependencies include '@mantine/form' for useForm. Key inputs are the initialValues object representing nested user, fruits, and deeply nested structures. Outputs include form helpers to get input properties, set values, and validate nested fields with dot-notation paths. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/nested.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    user: {
      firstName: 'John',
      lastName: 'Doe',
    },

    fruits: [
      { name: 'Banana', available: true },
      { name: 'Orange', available: false },
    ],

    deeply: {
      nested: {
        object: [{ item: 1 }, { item: 2 }],
      },
    },
  },
});

// Props for input that is controlled by user object firstName field
form.getInputProps('user.firstName');

// Set value of `name` field that is contained in object at second position of fruits array:
form.setFieldValue('fruits.1.name', 'Carrot');

// Validate deeply nested field
form.validateField('deeply.nested.object.0.item');

TITLE: Defining the useEventListener Hook in React (TypeScript) DESCRIPTION: Defines a generic TypeScript hook named useEventListener that attaches an event listener to a DOM element associated with a provided ref. The hook takes the event type (as a key of HTMLElementEventMap), a listener function receiving the event, and optional event listener options (either boolean or AddEventListenerOptions). On component unmount, the event listener is automatically removed to avoid memory leaks or duplicated listeners. Required dependencies are React and appropriate type definitions. Expected input parameters are the event type string, a callback function, and optional settings; the hook returns a mutable ref to the target element. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-event-listener.mdx#_snippet_0

LANGUAGE: TSX CODE:

function useEventListener<
  K extends keyof HTMLElementEventMap,
  T extends HTMLElement = any,
>(
  type: K,
  listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any,
  options?: boolean | AddEventListenerOptions
): MutableRefObject<T>;

TITLE: Corrected usage of hooks with 'use client' directive in TypeScript DESCRIPTION: This code snippet shows how to properly use the useDisclosure hook in a Mantine component by adding the 'use client' directive at the top, allowing hook usage in client components without errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_1

LANGUAGE: TypeScript CODE:

// ✅ No error
'use client';

import { useDisclosure } from '@mantine/hooks';

function Demo() {
  const { opened, toggle } = useDisclosure();
  return (
    <button onClick={toggle}>{opened ? 'Opened' : 'Closed'}</button>
  );
}

TITLE: Proper hook usage in a client component with 'use client' directive DESCRIPTION: This code demonstrates correct React hook usage in a Mantine component by adding 'use client' at the top, which enables the usage of hooks like useRef without errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_5

LANGUAGE: TypeScript CODE:

// ✅ No error
'use client';

import { useRef } from 'react';

function Demo() {
  const ref = useRef();
}

TITLE: Comparing useEffect and useShallowEffect Dependency Comparison in React DESCRIPTION: Demonstrates the difference between standard React useEffect and Mantine's useShallowEffect when using object dependencies. useEffect uses referential equality, potentially causing re-renders when the object reference changes, while useShallowEffect uses shallow equality, preventing re-renders if the object content is shallowly the same. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-shallow-effect.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useEffect } from 'react';
import { useShallowEffect } from '@mantine/hooks';

// Will be called on each render
useEffect(() => {}, [{ a: 1 }]);

// Will be called only once
useShallowEffect(() => {}, [{ a: 1 }]);

TITLE: Validating with Zod using useForm DESCRIPTION: This snippet demonstrates basic form validation using Zod with Mantine Form. It defines a schema for validating name, email, and age fields, then uses zodResolver to integrate the schema with the form. The useForm hook is used to manage form state and validation, demonstrating how to access validation errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { zodResolver } from 'mantine-form-zod-resolver';
import { z } from 'zod';
import { useForm } from '@mantine/form';

const schema = z.object({
  name: z
    .string()
    .min(2, { message: 'Name should have at least 2 letters' }),
  email: z.string().email({ message: 'Invalid email' }),
  age: z.number().min(18, {
    message: 'You must be at least 18 to create an account',
  }),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    name: '',
    email: '',
    age: 16,
  },
  validate: zodResolver(schema),
});

form.validate();
form.errors;
// -> {
//  name: 'Name should have at least 2 letters',
//  email: 'Invalid email',
//  age: 'You must be at least 18 to create an account'
// }

TITLE: Validating with Yup using useForm DESCRIPTION: This code snippet showcases how to perform form validation using Yup with Mantine Form. It sets up a Yup schema for validating name, email, and age and integrates it with useForm using yupResolver. The example demonstrates the retrieval of validation errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { yupResolver } from 'mantine-form-yup-resolver';
import * as yup from 'yup';
import { useForm } from '@mantine/form';

const schema = yup.object().shape({
  name: yup.string().min(2, 'Name should have at least 2 letters'),
  email: yup
    .string()
    .required('Invalid email')
    .email('Invalid email'),
  age: yup
    .number()
    .min(18, 'You must be at least 18 to create an account'),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    name: '',
    email: '',
    age: 16,
  },
  validate: yupResolver(schema),
});

form.validate();
form.errors;
// -> {
//  name: 'Name should have at least 2 letters',
//  email: 'Invalid email',
//  age: 'You must be at least 18 to create an account'
// }

TITLE: Removing Mantine Carousel useAnimationOffsetEffect Hook (TSX) DESCRIPTION: Explains that the useAnimationOffsetEffect hook was removed in Mantine Carousel 8.x and is no longer required, demonstrating its removal from the code. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/7x-to-8x.mdx#_snippet_15

LANGUAGE: tsx CODE:

// ❌ 7.x – useAnimationOffsetEffect is no longer available in 8.x
import { Carousel, Embla, useAnimationOffsetEffect } from '@mantine/carousel';
import { useState } from 'react';

const TRANSITION_DURATION = 500; // Example constant

function Demo7x() {
  const [embla, setEmbla] = useState<Embla | null>(null);
  useAnimationOffsetEffect(embla, TRANSITION_DURATION);
  return <Carousel getEmblaApi={setEmbla} />;
}

// ✅ 8.x – remove useAnimationOffsetEffect entirely, it is not required
import { Carousel } from '@mantine/carousel';

function Demo8x() {
  return <Carousel />;
}

TITLE: Defining a Custom Input Component for Mantine Form (TypeScript) DESCRIPTION: This snippet provides the interface and implementation for a CustomInput component designed to be compatible with Mantine's form.getInputProps. It explicitly defines props like value, onChange, onFocus, onBlur, and error, ensuring that the component can correctly receive and utilize the properties returned by getInputProps. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/get-input-props.mdx#_snippet_2

LANGUAGE: tsx CODE:

interface CustomInputProps {
  value?: string;
  defaultValue?: string;
  onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;
  onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;
  error?: string;
}

export function CustomInput({
  value,
  defaultValue,
  onChange,
  onFocus,
  onBlur,
  error,
}: CustomInputProps) {
  return (
    <div>
      <input
        value={value}
        defaultValue={defaultValue}
        onChange={onChange}
        onFocus={onFocus}
        onBlur={onBlur}
      />
      {error && <div>{error}</div>}
    </div>
  );
}

TITLE: Creating a Typed Form with useForm Hook in Mantine (TypeScript/React) DESCRIPTION: Shows how to initialize a typed form using the useForm hook from '@mantine/form' in React. The form state is managed for an interface DemoFormValues with 'name' and 'age' fields. Assigns a unique name to allow global actions, sets initial values, and configures the form for subsequent external state modifications. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.2.0.md#_snippet_1

LANGUAGE: TypeScript CODE:

import { useForm } from '@mantine/form';

export interface DemoFormValues {
  name: string;
  age: number;
}

function Demo() {
  const form = useForm<DemoFormValues>({
    name: 'demo-form',
    initialValues: {
      name: '',
      age: 0,
    },
  });
}

TITLE: Extending Regular Mantine Component Props (TypeScript) DESCRIPTION: Shows how to extend the props type of a regular Mantine component (Group) by creating a new interface (MyGroupProps) that extends the component's original props (GroupProps) and adds custom properties (spacing). The example then uses this extended type in a functional component. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { Group, GroupProps } from '@mantine/core';

// Interface includes `React.ComponentPropsWithoutRef<'div'>`
interface MyGroupProps extends GroupProps {
  spacing: number;
}

function MyGroup({ spacing, ...others }: MyGroupProps) {
  return <Group my={spacing} {...others} />;
}

TITLE: Using MantineProvider with Custom Theme in React (TypeScript) DESCRIPTION: Demonstrates how to wrap your application with MantineProvider while passing a custom theme object. It covers importing modules, creating a theme with customized font and primary color, and embedding the provider at the app root to apply the theme across all components. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/mantine-provider.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  fontFamily: 'Open Sans, sans-serif',
  primaryColor: 'cyan',
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Implementing Accessibility for Stepper Components in React DESCRIPTION: Shows how to make Stepper.Step components accessible for screen readers by providing proper labels. Includes examples of correct and incorrect usage patterns for accessibility compliance. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/stepper.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { Stepper } from '@mantine/core';

function Demo() {
  return (
    <Stepper active={0}>
      {/* Not ok, no label for screen reader */}
      <Stepper.Step />

      {/* Ok, label and description */}
      <Stepper.Step label="Step 1" description="Create an account" />

      {/* Ok, aria-label */}
      <Stepper.Step aria-label="Create an account" />
    </Stepper>
  );
}

TITLE: Controlled Textarea in React DESCRIPTION: This example demonstrates how to create a controlled Textarea component in React using the useState hook to manage the textarea's value. The onChange event handler updates the state with the current value of the textarea. The component uses the Textarea component from the '@mantine/core' library. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/textarea.mdx#_snippet_0

LANGUAGE: typescript CODE:

import { useState } from 'react';
import { Textarea } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('');
  return (
    <Textarea
      value={value}
      onChange={(event) => setValue(event.currentTarget.value)}
    />
  );
}

TITLE: Setting Up MantineProvider in _app.tsx DESCRIPTION: Initializes MantineProvider in the Next.js custom App component, passing a theme object and wrapping the entire application to provide Mantine styling and theming. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/next.mdx#_snippet_5

LANGUAGE: TypeScript CODE:

import '@mantine/core/styles.css';

import type { AppProps } from 'next/app';
import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  /** Put your mantine theme override here */
});

export default function App({ Component, pageProps }: AppProps) {
  return (
    <MantineProvider theme={theme}>
      <Component {...pageProps} />
    </MantineProvider>
  );
}

TITLE: Customizing Mantine Theme with createTheme and MantineProvider (TSX) DESCRIPTION: Demonstrates how to create a custom theme object using createTheme and apply it to the application by wrapping the root component with MantineProvider. Shows examples of overriding colors, shadows, and headings. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/theme-object.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  colors: {
    // Add your color
    deepBlue: [
      '#eef3ff',
      '#dce4f5',
      '#b9c2de',
      '#98a0ca',
      '#7a84ba',
      '#6672b0',
      '#5c68ac',
      '#4c5897',
      '#424e88',
      '#364379'
    ],
    // or replace default theme color
    blue: [
      '#eef3ff',
      '#dee2f2',
      '#bdc2de',
      '#98a0ca',
      '#7a84ba',
      '#6672b0',
      '#5c68ac',
      '#4c5897',
      '#424e88',
      '#364379'
    ]
  },

  shadows: {
    md: '1px 1px 3px rgba(0, 0, 0, .25)',
    xl: '5px 5px 3px rgba(0, 0, 0, .25)'
  },

  headings: {
    fontFamily: 'Roboto, sans-serif',
    sizes: {
      h1: { fontSize: 36 }
    }
  }
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Implementing Dynamic Employee List with Mantine use-form in React DESCRIPTION: This example demonstrates how to implement a dynamic list of employee objects using Mantine's use-form hook. The component allows adding, removing, and editing employee information with name and active status fields. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/list-of-strings-in-use-form.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { IconTrash } from '@tabler/icons-react';
import {
  ActionIcon,
  Box,
  Button,
  Group,
  Switch,
  Text,
  TextInput,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { randomId } from '@mantine/hooks';

function Demo() {
  const form = useForm({
    mode: 'uncontrolled',
    initialValues: {
      employees: [{ name: '', active: false, key: randomId() }],
    },
  });

  const fields = form.getValues().employees.map((item, index) => (
    <Group key={item.key} mt="xs">
      <TextInput
        placeholder="John Doe"
        withAsterisk
        style={{ flex: 1 }}
        key={form.key(`employees.${index}.name`)}
        {...form.getInputProps(`employees.${index}.name`)}
      />
      <Switch
        label="Active"
        key={form.key(`employees.${index}.active`)}
        {...form.getInputProps(`employees.${index}.active`, {
          type: 'checkbox',
        })}
      />
      <ActionIcon
        color="red"
        onClick={() => form.removeListItem('employees', index)}
      >
        <IconTrash size="1rem" />
      </ActionIcon>
    </Group>
  ));

  return (
    <Box maw={500} mx="auto">
      {fields.length > 0 ? (
        <Group mb="xs">
          <Text fw={500} size="sm" style={{ flex: 1 }}>
            Name
          </Text>
          <Text fw={500} size="sm" pr={90}>
            Status
          </Text>
        </Group>
      ) : (
        <Text c="dimmed" ta="center">
          No one here...
        </Text>
      )}

      {fields}

      <Group justify="center" mt="md">
        <Button
          onClick={() =>
            form.insertListItem('employees', {
              name: '',
              active: false,
              key: randomId(),
            })
          }
        >
          Add employee
        </Button>
      </Group>
    </Box>
  );
}

TITLE: Checking Dropdown Opened State in Mantine Select Using React Testing Library (TypeScript/TSX) DESCRIPTION: This example verifies the open/closed visual state of a Mantine Select dropdown by asserting presence and visibility of elements with role 'listbox'. The test consists of checking that the dropdown is initially closed, then opening it via userEvent.click, and finally asserting the dropdown is visible. Prerequisites include Mantine's Select, React Testing Library (with render, userEvent, screen), and a test runner like Jest or Vitest. The item's label is used to get the correct element by role. This pattern ensures that input focus and accessibility behaviors are functioning as intended. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/combobox-testing.mdx#_snippet_3

LANGUAGE: TSX CODE:

import { Select } from '@mantine/core';

function MyForm() {
  return (
    <Select
      name="age"
      label="Select your age"
      data=[
        { value: 'ok', label: 'I am 18 or older' },
        { value: 'not-ok', label: 'I am under 18' },
      ]
    />
  );
}

it('verifies dropdown opened state', () => {
  render(<MyForm />);

  // Verify that dropdown is closed
  // Listbox has the same name as the textbox
  expect(screen.queryByRole('listbox', { name: 'Select your age' })).toBeNull();

  // Click Select to open the options list
  await userEvent.click(screen.getByRole('textbox', { name: 'Select your age' }));

  // Verify that dropdown is open
  expect(screen.getByRole('listbox', { name: 'Select your age' })).toBeVisible();
});

TITLE: Setting Up MantineProvider in React Router Root Layout (TSX) DESCRIPTION: Illustrates how to modify the app/root.tsx file in a React Router application to integrate Mantine. It involves importing core Mantine styles, adding the ColorSchemeScript to the head for theme management, applying mantineHtmlProps to the html tag, and wrapping the main application outlet (children) with the MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/react-router.mdx#_snippet_2

LANGUAGE: typescript CODE:

// Import styles of packages that you've installed.
// All packages except `@mantine/hooks` require styles imports
import '@mantine/core/styles.css';

import {
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from "react-router";
import { ColorSchemeScript, MantineProvider, mantineHtmlProps } from '@mantine/core';

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" {...mantineHtmlProps}>
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <ColorSchemeScript />
        <Meta />
        <Links />
      </head>
      <body>
        <MantineProvider>{children}</MantineProvider>
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

// ... other app/root.tsx content

TITLE: Implementing Container Queries in Carousel Component in TypeScript React DESCRIPTION: Shows usage of container queries with Mantine's Carousel component by setting its type to 'container', enabling responsive slide sizes and gaps based on container width instead of viewport. The example wraps Carousel in a resizable div to demonstrate layout changes as container resizes, with customizable slideSize and slideGap properties targeting various width breakpoints. Requires React and @mantine/carousel package. Enhances responsive design flexibility by using container queries. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.16.0.md#_snippet_4

LANGUAGE: tsx CODE:

import { Carousel } from '@mantine/carousel';

function Demo() {
  return (
    // Wrapper div is added for demonstration purposes only,
    // It is not required in real projects
    <div
      style={{
        resize: 'horizontal',
        overflow: 'hidden',
        maxWidth: '100%',
        minWidth: 250,
        padding: 10,
      }}
    >
      <Carousel
        withIndicators
        height={200}
        type="container"
        slideSize={{ base: '100%', '300px': '50%', '500px': '33.333333%' }}
        slideGap={{ base: 0, '300px': 'md', '500px': 'lg' }}
        loop
        align="start"
      >
        <Carousel.Slide>1</Carousel.Slide>
        <Carousel.Slide>2</Carousel.Slide>
        <Carousel.Slide>3</Carousel.Slide>
        {/* ...other slides */}
      </Carousel>
    </div>
  );
}

TITLE: Transforming Form Values before Submission DESCRIPTION: Demonstrates how to use transformValues to transform form values before they get submitted. This example shows how to get transformed values programmatically using getTransformedValues. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/values.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    mode: 'uncontrolled',
    initialValues: {
      firstName: 'John',
      lastName: 'Doe',
    },

    transformValues: (values) => ({
      fullName: `${values.firstName} ${values.lastName}`,
    }),
  });

  form.getTransformedValues(); // -> { fullName: 'John Doe' }
  form.getTransformedValues({
    firstName: 'Jane',
    lastName: 'Loe',
  }); // { fullName: 'Jane Loe' }
}

TITLE: Form Validation with zodResolver (React, TypeScript) DESCRIPTION: Implements schema-based form validation using zodResolver in a Mantine form. Requires '@mantine/form', 'zod', and 'mantine-form-zod-resolver' as dependencies. The form has fields for name, email, and age, validates on demand, and exposes errors for each field based on the schema. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.3.0.md#_snippet_4

LANGUAGE: tsx CODE:

import { zodResolver } from 'mantine-form-zod-resolver';
import { z } from 'zod';
import { useForm } from '@mantine/form';

const schema = z.object({
  name: z.string().min(2, { message: 'Name should have at least 2 letters' }),
  email: z.string().email({ message: 'Invalid email' }),
  age: z.number().min(18, { message: 'You must be at least 18 to create an account' }),
});

const form = useForm({
  initialValues: {
    name: '',
    email: '',
    age: 16,
  },
  validate: zodResolver(schema),
});

form.validate();
form.errors;
// -> {
//  name: 'Name should have at least 2 letters',
//  email: 'Invalid email',
//  age: 'You must be at least 18 to create an account'
// }

TITLE: Implementing Controlled SegmentedControl with React DESCRIPTION: This snippet demonstrates how to implement a controlled SegmentedControl component using React's state management. It uses the useState hook to manage the selected value. The component renders a segmented control with options for React, Angular, Vue, and Svelte, updating the state based on user interactions. The value prop receives the selected value, and onChange updates the state. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/segmented-control.mdx#_snippet_0

LANGUAGE: tsx CODE:

```tsx
import { useState } from 'react';
import { SegmentedControl } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('react');

  return (
    <SegmentedControl
      value={value}
      onChange={setValue}
      data={[
        { label: 'React', value: 'react' },
        { label: 'Angular', value: 'ng' },
        { label: 'Vue', value: 'vue' },
        { label: 'Svelte', value: 'svelte' },
      ]}
    />
  );
}

----------------------------------------

TITLE: Defining Local Fonts with @font-face in CSS
DESCRIPTION: This CSS snippet defines `@font-face` rules to load local font files (`.woff2`) for the 'Roboto' font family, specifying different weights (700 and 900) and formats. It should be placed in a CSS file that is then imported into the application.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/vite-load-fonts.mdx#_snippet_0

LANGUAGE: css
CODE:

@font-face { font-family: 'Roboto'; src: url('./Roboto-Bold.woff2') format('woff2'); font-weight: 700; font-style: normal; }

@font-face { font-family: 'Roboto'; src: url('./Roboto-Heavy.woff2') format('woff2'); font-weight: 900; font-style: normal; }


----------------------------------------

TITLE: Updating Initial Form Values with Mantine Form (TSX)
DESCRIPTION: This example demonstrates how to use `form.setInitialValues` and `form.setValues` within a React `useEffect` hook to populate a Mantine form with data fetched asynchronously. It shows how to update both the current form values and the initial values used for reset and dirty state tracking.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-1-0.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { useEffect } from 'react'; import { useForm } from '@mantine/form';

function Demo() { const form = useForm({ initialValues: { name: '', email: '', }, });

useEffect(() => { fetch('/api/user') .then((res) => res.json()) .then((data) => { // Update initial values after form was initialized // These values will be used in form.reset // and to compare values to get dirty state form.setInitialValues(data); form.setValues(data); }); }, []); }


----------------------------------------

TITLE: Validating nested object values with Mantine useForm hook in TypeScript
DESCRIPTION: Illustrates validation of nested object fields during form interaction using useForm's validate option. The snippet defines validation functions for nested fields user.name and user.occupation enforcing minimum length constraints. It shows how to invoke generic validate() to trigger validations and access resulting errors keyed by dot-separated field paths. Requires '@mantine/form' and expects 'user' object with string fields in initial values input. Outputs validation error messages if constraints fail.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/nested.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { user: { name: '', occupation: '', }, },

validate: { user: { name: (value) => value.length < 2 ? 'Name is too short' : null, occupation: (value) => value.length < 2 ? 'Occupation is too short' : null, }, }, });

form.validate(); form.errors; // -> { 'user.name': 'Name is too short', 'user.occupation': 'Occupation is too short' }


----------------------------------------

TITLE: Ensuring Accessibility for Mantine Switch Component in TSX
DESCRIPTION: Provides guidance and examples on making the Mantine `Switch` component accessible, emphasizing the need for proper labeling as it renders a standard `input[type="checkbox"]`. It shows incorrect usage (without any label or `aria-label`) and correct usage (using `aria-label` or the `label` prop) to ensure assistive technologies can interpret the switch's purpose. Requires `react` and `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/switch.mdx#_snippet_4

LANGUAGE: tsx
CODE:

import { Switch } from '@mantine/core';

// -> not ok, input is not labeled function Bad() { return <Switch />; }

// -> ok, input has aria-label function Good() { return <Switch aria-label="I agree to everything" />; }

// -> ok, input has associated label function AlsoGood() { return <Switch label="I agree to everything" />; }


----------------------------------------

TITLE: DateTimePicker 8.x timePickerProps Usage
DESCRIPTION: Example demonstrating the correct way to pass props to the underlying TimePicker component in Mantine 8.x using the new `timePickerProps` prop, replacing the deprecated `timeInputProps`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/7x-to-8x.mdx#_snippet_8

LANGUAGE: tsx
CODE:

import { DateTimePicker } from '@mantine/dates';

function Demo() { return ( <DateTimePicker // ✅ Use timePickerProps instead of timeInputProps timePickerProps={{ leftSection: <IconClock size={16} stroke={1.5} />, minutesStep: 5, withDropdown: true, }} /> ); }


----------------------------------------

TITLE: Mocking Browser APIs for jsdom with Vitest (TypeScript)
DESCRIPTION: This snippet creates a vitest.setup.mjs setup file that mocks browser APIs such as matchMedia and ResizeObserver, which are unavailable in jsdom but required for some Mantine components. It also patches scrollIntoView and getComputedStyle to avoid test failures. The only required dependency is '@testing-library/jest-dom/vitest' and vitest itself. The setup ensures components dependent on these APIs will not throw errors during tests. Place this file in the project root as referenced in the Vitest configuration.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/vitest.mdx#_snippet_1

LANGUAGE: TypeScript
CODE:

import '@testing-library/jest-dom/vitest';

import { vi } from 'vitest';

const { getComputedStyle } = window; window.getComputedStyle = (elt) => getComputedStyle(elt); window.HTMLElement.prototype.scrollIntoView = () => {};

Object.defineProperty(window, 'matchMedia', { writable: true, value: vi.fn().mockImplementation((query) => ({ matches: false, media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), })), });

class ResizeObserver { observe() {} unobserve() {} disconnect() {} }

window.ResizeObserver = ResizeObserver;


----------------------------------------

TITLE: Failing React Testing Library Test for Mantine Modal (TSX)
DESCRIPTION: This snippet shows a React Testing Library test for the AuthModal component that fails when transitions are enabled. It attempts to click the button to open the modal and then assert that the modal's heading is present in the document. The test fails because the transition component uses setTimeout, which @testing-library/react doesn't wait for by default, causing the modal content to not be in the DOM immediately after the click event is processed.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/portals-testing.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { render, screen, userEvent } from '@/test-utils'; import { AuthModal } from './AuthModal';

describe('AuthModal', () => { it('opens modal when button is clicked', async () => { render(<AuthModal />); await userEvent.click(screen.getByRole('button', { name: 'Open authentication modal' })); // ⛔ Test fails, modal heading is not in the document yet // Error message: TestingLibraryElementError: Unable to find an accessible element // with the role "heading" and name "Authenticate" expect(screen.getByRole('heading', { name: 'Authenticate' })).toBeInTheDocument(); }); });


----------------------------------------

TITLE: Configuring React Testing Library with Mantine Theme for Tests (TSX)
DESCRIPTION: This snippet provides a custom render function designed for testing Mantine components with React Testing Library. It uses MantineProvider and a merged theme (testTheme) that overrides the default Modal component's defaultProps to set transitionProps.duration to 0. This effectively disables transitions during tests, resolving issues where tests fail due to components not being immediately available in the DOM after state changes triggered by user events. It requires @testing-library/react, @mantine/core, and access to the project's main theme.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/portals-testing.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { render as testingLibraryRender } from '@testing-library/react'; import { createTheme, MantineProvider, mergeThemeOverrides, Modal } from '@mantine/core'; // Your project theme import { theme } from '../theme';

// Merge your project theme with tests specific overrides const testTheme = mergeThemeOverrides( theme, createTheme({ components: { Modal: Modal.extend({ defaultProps: { transitionProps: { duration: 0 }, }, }), }, }) );

export function render(ui: React.ReactNode) { return testingLibraryRender(<>{ui}</>, { wrapper: ({ children }: { children: React.ReactNode }) => ( <MantineProvider theme={testTheme}>{children}</MantineProvider> ), }); }


----------------------------------------

TITLE: Extending MantineThemeOther Interface (TSX)
DESCRIPTION: This snippet shows how to extend the MantineThemeOther interface in a .d.ts file to add custom properties and functions to the theme.other object. This provides type safety and editor autocomplete for these custom additions.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_8

LANGUAGE: tsx
CODE:

// mantine.d.ts declare module '@mantine/core' { export interface MantineThemeOther { myCustomProperty: string; myCustomFunction: () => void; } }


----------------------------------------

TITLE: Adding Typesafety to Context Modals in TypeScript with Module Declaration
DESCRIPTION: Enhances typesafety by declaring a module augmentation for '@mantine/modals', overriding MantineModalsOverride interface with a strongly typed modals object. This enables TypeScript to enforce modal keys and innerProps types, improving developer experience and preventing runtime errors when using openContextModal. ModalsProvider receives the typed modals object.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/modals.mdx#_snippet_3

LANGUAGE: tsx
CODE:

const TestModal = ({ context, id, innerProps, }: ContextModalProps<{ modalBody: string }>) => ( <> <Text size="sm">{innerProps.modalBody}</Text> <Button fullWidth mt="md" onClick={() => context.closeModal(id)}> Close modal </Button> </> ); const modals = { demonstration: TestModal, /* ...other modals / }; declare module '@mantine/modals' { export interface MantineModalsOverride { modals: typeof modals; } } function Demo() { return ( <ModalsProvider modals={modals}> {/ Your app here */} </ModalsProvider> ); }


----------------------------------------

TITLE: Using useUncontrolled for a Custom Input Component (TSX)
DESCRIPTION: Demonstrates implementing a custom input component in React using the `useUncontrolled` hook. The hook manages the input's state, accepting `value`, `defaultValue`, `finalValue`, and an `onChange` handler, returning the current value and a change handler function.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-uncontrolled.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useUncontrolled } from '@mantine/hooks';

interface CustomInputProps { value?: string; defaultValue?: string; onChange?: (value: string) => void; }

function CustomInput({ value, defaultValue, onChange, }: CustomInputProps) { const [_value, handleChange] = useUncontrolled({ value, defaultValue, finalValue: 'Final', onChange, });

return ( <input type="text" value={_value} onChange={(event) => handleChange(event.currentTarget.value)} /> ); }


----------------------------------------

TITLE: Replacing compound components with regular components to avoid errors
DESCRIPTION: This code demonstrates an alternative approach by importing and using non-compound versions of Mantine components (e.g., `PopoverTarget`) which can be used in server components without `'use client'`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_8

LANGUAGE: TypeScript
CODE:

// ✅ No error, no 'use client' needed import { Popover, PopoverTarget } from '@mantine/core';

function Demo() { return ( <Popover> <PopoverTarget> <button>Toggle popover</button> </PopoverTarget> </Popover> ); }


----------------------------------------

TITLE: Importing Mantine Core Styles (TSX)
DESCRIPTION: Demonstrates how to import the required core Mantine styles into the root file of an application, typically in `_app.tsx` for Next.js pages router. It also shows commented-out examples for importing styles from other Mantine packages.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/getting-started.mdx#_snippet_1

LANGUAGE: TypeScript
CODE:

// core styles are required for all packages import '@mantine/core/styles.css';

// other css files are required only if // you are using components from the corresponding package // import '@mantine/dates/styles.css'; // import '@mantine/dropzone/styles.css'; // import '@mantine/code-highlight/styles.css'; // ...


----------------------------------------

TITLE: Customizing Year/Month Control Aria Labels with Callbacks (tsx)
DESCRIPTION: Shows how to use the `getYearControlProps` and `getMonthControlProps` functions to dynamically set the `aria-label` attribute for individual year and month controls based on their date value in the Mantine MonthPicker component.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/month-picker.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { MonthPicker } from '@mantine/dates';

function Demo() { return ( <MonthPicker getYearControlProps={(date) => ({ 'aria-label': Select year ${date.getFullYear()}, })} getMonthControlProps={(date) => ({ 'aria-label': Select month ${date.getFullYear()}/${date.getMonth()}, })} /> ); }


----------------------------------------

TITLE: Creating Custom Form Components with Uncontrolled Mode Support
DESCRIPTION: Implementation of a custom form input component that supports both controlled and uncontrolled modes using the use-uncontrolled hook.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/uncontrolled.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { useUncontrolled } from '@mantine/hooks';

interface CustomInputProps { value?: string; defaultValue?: string; onChange?: (value: string) => void; }

// ✅ CustomInput supports both controlled and uncontrolled modes function CustomInput({ value, defaultValue, onChange, }: CustomInputProps) { const [_value, handleChange] = useUncontrolled({ value, defaultValue, finalValue: 'Final', onChange, });

return ( <input type="text" value={_value} onChange={(event) => handleChange(event.currentTarget.value)} /> ); }

function Demo() { const form = useForm({ mode: 'uncontrolled', initialValues: { text: 'Initial' }, });

// ✅ CustomInput supports defaultValue prop, // it can be used in uncontrolled mode return ( <CustomInput {...form.getInputProps('text')} key={form.key('text')} /> ); }


----------------------------------------

TITLE: Creating a Custom Input with Controlled and Uncontrolled Modes using Mantine and React - TypeScript
DESCRIPTION: This snippet defines a React functional component, CustomInput, which supports both controlled and uncontrolled usage by leveraging the useUncontrolled hook from @mantine/hooks. It accepts value, defaultValue, and onChange props, allowing integration with form libraries like @mantine/form. Dependencies include @mantine/hooks and React. The component expects string values and calls onChange when the input value changes. It outputs a standard input[type=text] element. Limitations: this component does not directly support error states or additional props required by form libraries unless further extended.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/custom-input-use-form.mdx#_snippet_0

LANGUAGE: TSX
CODE:

import { useUncontrolled } from '@mantine/hooks';

interface CustomInputProps { value?: string; defaultValue?: string; onChange?: (value: string) => void; }

function CustomInput({ value, defaultValue, onChange, }: CustomInputProps) { const [_value, handleChange] = useUncontrolled({ value, defaultValue, finalValue: 'Final', onChange, });

return ( <input type="text" value={_value} onChange={(event) => handleChange(event.currentTarget.value)} /> ); }


----------------------------------------

TITLE: Tracking Form Submission State with useForm - Mantine Form Hook in React TypeScript
DESCRIPTION: Example of utilizing form.submitting and form.setSubmitting features of Mantine's useForm hook. Demonstrates auto-tracking of submission state when the onSubmit handler returns a Promise, as well as manual control of submitting state. Requires @mantine/form for useForm, @mantine/core for UI components. Shows disabling and loading states during async submission, and parameters for initialValues and form modes.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.15.0.md#_snippet_6

LANGUAGE: TSX
CODE:

import { useState } from 'react'; import { Button, Group, Stack, Text, TextInput } from '@mantine/core'; import { useForm } from '@mantine/form';

const asyncSubmit = (values: any) => new Promise((resolve) => setTimeout(() => resolve(values), 3000));

function Demo() { const form = useForm({ mode: 'uncontrolled', initialValues: { name: 'John' }, });

const [completed, setCompleted] = useState(false);

const handleSubmit = async (values: typeof form.values) => { await asyncSubmit(values); setCompleted(true); };

if (completed) { return ( <Stack> <Text>Form submitted!</Text> <Button onClick={() => setCompleted(false)}>Reset to initial state</Button> </Stack> ); }

return ( <form onSubmit={form.onSubmit(handleSubmit)}> <TextInput withAsterisk label="Name" placeholder="Your name" key={form.key('name')} disabled={form.submitting} {...form.getInputProps('name')} />

  <Group justify="flex-end" mt="md">
    <Button type="submit" loading={form.submitting}>
      Submit
    </Button>
  </Group>
</form>

); }


----------------------------------------

TITLE: Controlled MultiSelect State Management with React Hooks in TypeScript
DESCRIPTION: Demonstrates controlled usage of the MultiSelect component where the selected values are managed as a state array of strings using React's useState hook. The onChange callback updates the component's value state, enforcing that only arrays of strings are supported as selections. This snippet requires React and @mantine/core dependencies and showcases basic controlled input technique in TypeScript.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/multi-select.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { MultiSelect } from '@mantine/core';

function Demo() { const [value, setValue] = useState<string[]>([]); return <MultiSelect data={[]} value={value} onChange={setValue} />; }


----------------------------------------

TITLE: Controlled Tabs with Mantine
DESCRIPTION: Demonstrates how to create controlled Tabs component with Mantine, managing active tab state using `useState` hook. The `value` and `onChange` props are used to control the active tab and update the state on tab change. This approach is useful when you need to synchronize the Tabs state with other parts of the application.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tabs.mdx#_snippet_0

LANGUAGE: typescript
CODE:

import { useState } from 'react'; import { Tabs } from '@mantine/core';

function Demo() { const [activeTab, setActiveTab] = useState<string | null>('first');

return ( <Tabs value={activeTab} onChange={setActiveTab}> <Tabs.List> <Tabs.Tab value="first">First tab</Tabs.Tab> <Tabs.Tab value="second">Second tab</Tabs.Tab> </Tabs.List>

  <Tabs.Panel value="first">First panel</Tabs.Panel>
  <Tabs.Panel value="second">Second panel</Tabs.Panel>
</Tabs>

); }


----------------------------------------

TITLE: Controlled Pagination Example with React and Mantine
DESCRIPTION: Demonstrates how to create a controlled Pagination component in React using Mantine. It utilizes the `useState` hook to manage the active page and the `onChange` prop to update the state when the user interacts with the pagination controls. The `total` prop specifies the total number of pages.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/pagination.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { Pagination } from '@mantine/core';

function Demo() { const [activePage, setPage] = useState(1); return ( <Pagination value={activePage} onChange={setPage} total={10} /> ); }


----------------------------------------

TITLE: Correct TextInput Usage Example
DESCRIPTION: Illustrates the correct usage of `TextInput`, the preferred component for input fields.  It shows how `TextInput` provides accessibility and includes `Input.Wrapper` by default. Requires `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/input.mdx#_snippet_1

LANGUAGE: tsx
CODE:

// Use TextInput instead of Input everywhere you want to use Input, // it is accessible by default and includes Input.Wrapper function Correct() { return ( <TextInput label="Input label" description="Input description" /> ); }


----------------------------------------

TITLE: Initializing useForm Hook with Initial Values - Mantine (TypeScript/TSX)
DESCRIPTION: This snippet demonstrates how to initialize the useForm hook from @mantine/form with a comprehensive object containing nested fields and arrays. It does not require additional dependencies except for @mantine/form and works in uncontrolled mode. The initialValues parameter specifies the starting values for each form field. Expected input is the configuration object; output is a form instance with state and methods for further manipulation.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_0

LANGUAGE: TSX
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { path: '', path2: '', user: { firstName: 'John', lastName: 'Doe', }, fruits: [ { name: 'Banana', available: true }, { name: 'Orange', available: false }, ], accepted: false, }, });


----------------------------------------

TITLE: Handling Timezones with Mantine Dates and Day.js (React/TypeScript)
DESCRIPTION: This example illustrates how to integrate Mantine `@mantine/dates` components with a third-party date library like Day.js to manage timezones. Since Mantine 8.0 uses string values for dates without timezone information, this snippet shows how to convert the string value to a Day.js object to apply timezone adjustments.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/8-0-0.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import dayjs from 'dayjs'; import { DatePicker } from '@mantine/dates';

function Demo() { const [value, setValue] = useState<string | null>('2022-08-21');

// Mantine components use strings as values, you can pass these // strings to a dates library of your choice to assign timezone const dateWithTimeZone = dayjs(value).tz("America/Toronto").toDate();

return <DatePicker value={value} onChange={setValue} />; }


----------------------------------------

TITLE: Controlling Component Visibility with hiddenFrom/visibleFrom in Mantine (TSX)
DESCRIPTION: Illustrates the usage of `hiddenFrom` and `visibleFrom` props available on all Mantine components. These props accept a breakpoint value (`xs`, `sm`, `md`, `lg`, `xl`) to control component visibility based on the viewport width, hiding or showing the component when the width is less than or greater than the specified breakpoint respectively.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_29

LANGUAGE: tsx
CODE:

import { Button, Group } from '@mantine/core';

function Demo() { return ( <Group justify="center"> <Button hiddenFrom="sm" color="orange"> Hidden from sm </Button> <Button visibleFrom="sm" color="cyan"> Visible from sm </Button> <Button visibleFrom="md" color="pink"> Visible from md </Button> </Group> ); }


----------------------------------------

TITLE: Ensuring Application Styles Override Mantine with Correct Import Order in TypeScript
DESCRIPTION: Illustrates the correct and incorrect methods for importing custom application styles alongside Mantine styles in a TypeScript React application. Application CSS (e.g., Demo.module.css) must be imported after Mantine styles to ensure overrides. These imports are static and require the presence of a locally defined CSS module file.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/mantine-styles.mdx#_snippet_3

LANGUAGE: TypeScript
CODE:

// ✅ Correct order - your styles will override Mantine styles import '@mantine/core/styles.css'; import '@mantine/dates/styles.css'; import classes from './Demo.module.css';

// ❌ Incorrect order – Mantine styles will override your styles import classes from './Demo.module.css'; import '@mantine/core/styles.css'; import '@mantine/dates/styles.css';


----------------------------------------

TITLE: Using Mantine Box with Emotion sx Prop
DESCRIPTION: Demonstrates applying styles to a Mantine Box component using the Emotion `sx` prop. The `sx` prop accepts a function that receives the theme and utility functions, allowing for dynamic and responsive styling.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_7

LANGUAGE: TSX
CODE:

import { Box } from '@mantine/core';

function Demo() { return ( <Box sx={(theme, u) => ({ padding: 40,

    [u.light]: {
      backgroundColor: theme.colors.blue[0],
      color: theme.colors.blue[9],

      '&:hover': {
        backgroundColor: theme.colors.blue[1],
      },
    },
  })}
>
  Box with emotion sx prop
</Box>

); }


----------------------------------------

TITLE: Overriding Mantine Layered Styles with Local CSS in TypeScript
DESCRIPTION: Demonstrates the use of local application styles to override Mantine's layered styles by leveraging the CSS Cascade algorithm. Standard module.css imports placed after Mantine layered styles will override their rules. This approach requires having a custom CSS module (e.g., Demo.module.css) in the project.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/mantine-styles.mdx#_snippet_7

LANGUAGE: TypeScript
CODE:

// ✅ If your styles are not wrapped in @layer directive, // they will be applied after Mantine styles import classes from './Demo.module.css';

import '@mantine/core/styles.layer.css';


----------------------------------------

TITLE: Customizing Mantine Component with extend (TSX)
DESCRIPTION: Shows how to use the static `extend` function available on Mantine components like `TextInput` to define custom styles, classNames, and defaultProps directly within the `createTheme` configuration. This allows for better autocomplete and organization of component customizations.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-0-0.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { createTheme, MantineProvider, TextInput, } from '@mantine/core'; import classes from './Demo.module.css';

const theme = createTheme({ components: { TextInput: TextInput.extend({ styles: (t, props) => ({ input: { fontSize: props.size === 'compact' ? t.fontSizes.sm : undefined, }, }), classNames: { root: classes.root, input: classes.input, label: classes.label, },

  defaultProps: {
    size: 'compact',
  },
}),

}, });

function Demo() { return ( <MantineProvider theme={theme}> {/* Your app here */} </MantineProvider> ); }


----------------------------------------

TITLE: Validating with Superstruct using useForm
DESCRIPTION: This snippet demonstrates form validation using Superstruct with Mantine Form. It defines a Superstruct schema for validating name, email, and age and then uses `superstructResolver` to integrate with the form.  The example then shows how to access and interpret the errors.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_9

LANGUAGE: tsx
CODE:

import isEmail from 'is-email'; import { superstructResolver } from 'mantine-form-superstruct-resolver'; import * as s from 'superstruct';

const emailString = s.define('email', isEmail);

const schema = s.object({ name: s.size(s.string(), 2, 30), email: emailString, age: s.min(s.number(), 18), });

const form = useForm({ mode: 'uncontrolled', initialValues: { name: '', email: '', age: 16, }, validate: superstructResolver(schema), });

form.validate(); form.errors; // -> { // name: 'name: Expected a string with a length between 2 and 30 but received one with a length of 0', // email: 'email: Expected a value of type email, but received: ""', // age: 'age: Expected a number greater than or equal to 18 but received 16', // }


----------------------------------------

TITLE: Providing Custom Root Element for Color Scheme Data Attribute (TypeScript)
DESCRIPTION: Defines a function to return a specific DOM element (like document.body) to attach 'data-mantine-color-scheme', controlling where the color scheme data attribute is set, supporting hydration and SSR scenarios.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/mantine-provider.mdx#_snippet_6

LANGUAGE: TypeScript
CODE:

import { MantineProvider } from '@mantine/core';

const getRootElement = () => typeof window === 'undefined' ? undefined : document.body;

function Demo() { return ( <MantineProvider getRootElement={getRootElement}> {/* Your app here */} </MantineProvider> ); }


----------------------------------------

TITLE: Uploading Files from Mantine Dropzone to AWS S3 with React and Axios (TSX)
DESCRIPTION: This TypeScript React snippet demonstrates uploading a file dropped into the Mantine Dropzone component to an AWS S3 bucket using the Axios HTTP client. It manages the loading state to provide user feedback, triggers notifications upon success or failure of the upload, and uses the Dropzone component's onDrop event to call the upload handler. The snippet requires Mantine Dropzone, Axios, Mantine notifications, and React hooks. Input is a File object obtained from the Dropzone, and no output is returned from the UI component apart from visual state and notifications.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/dropzone-upload.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import axios from 'axios'; import { useState } from 'react'; import { Dropzone } from '@mantine/dropzone'; import { notifications } from '@mantine/notifications';

function Demo() { const [loading, setLoading] = useState(false);

const handleUpload = (file: File) => { setLoading(true);

axios
  .put('https://your-bucket.s3.amazonaws.com', file)
  .then(() => {
    notifications.showNotification({
      title: 'File uploaded',
      message: 'File uploaded successfully',
      color: 'teal',
    });
  })
  .catch((error) => {
    notifications.showNotification({
      title: 'File upload failed',
      message: error.message,
      color: 'red',
    });
  })
  .finally(() => setLoading(false));

};

return ( <Dropzone onDrop={(files) => handleUpload(files[0])} loading={loading}> {loading ? 'Uploading file...' : 'Drop file here'} </Dropzone> ); }


----------------------------------------

TITLE: Selecting Multiple Options with Mantine MultiSelect Using React Testing Library (TypeScript/TSX)
DESCRIPTION: This snippet showcases how to test selection of multiple options in Mantine's MultiSelect component using React Testing Library and userEvent. The test sample covers rendering a MultiSelect, opening the dropdown, selecting several options, and validating the value sent with a form submit. Dependencies include Mantine's MultiSelect, React Testing Library (render, screen, userEvent), and a testing framework such as Jest or Vitest. Data passed to 'data' prop should be an array of objects with 'value' and 'label'. The hidden input's value is asserted to ensure all selected items are correctly serialized.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/combobox-testing.mdx#_snippet_1

LANGUAGE: TSX
CODE:

import { MultiSelect } from '@mantine/core';

function MyForm() { return ( <MultiSelect name="groceries" label="Select groceries" data=[ { value: 'banana', label: 'Banana' }, { value: 'apple', label: 'Apple' }, { value: 'orange', label: 'Orange' }, ] /> ); }

it('selects multiple options', () => { render(<MyForm />);

// Click Select to open the options list // Note that unlike Select, MultiSelect does not close the dropdown when one of the options is selected // You can select several options one after another without clicking the input again await userEvent.click(screen.getByRole('textbox', { name: 'Select groceries' }));

// Click several options to select them await userEvent.click(screen.getByRole('option', { name: 'Banana' })); await userEvent.click(screen.getByRole('option', { name: 'Apple' }));

// The best way to verify that options are selected is to check the hidden input value expect(document.querySelector('input[name="groceries"]')).toHaveValue('banana,apple'); });


----------------------------------------

TITLE: Integrating Form with TanStack Query
DESCRIPTION: Demonstrates using form.initialize to sync form values with backend API response using TanStack Query (react-query). The form will be initialized only once even if query.data changes.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/values.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { useEffect } from 'react'; import { useQuery } from '@tanstack/react-query'; import { useForm } from '@mantine/form';

function Demo() { const query = useQuery({ queryKey: ['current-user'], queryFn: () => fetch('/api/users/me').then((res) => res.json()), });

const form = useForm({ mode: 'uncontrolled', initialValues: { name: '', email: '', }, });

useEffect(() => { if (query.data) { // Even if query.data changes, form will be initialized only once form.initialize(query.data); } }, [query.data]); }


----------------------------------------

TITLE: Using form.initialize with TanStack Query
DESCRIPTION: This snippet demonstrates using `form.initialize` to populate form values with data fetched using TanStack Query (react-query).  It uses `@tanstack/react-query`, `@mantine/form`, and `@mantine/core`. The `query.data` changes trigger re-initialization of the form.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_12

LANGUAGE: tsx
CODE:

import { useEffect } from 'react'; import { useQuery } from '@tanstack/react-query'; import { useForm } from '@mantine/form';

function Demo() { const query = useQuery({ queryKey: ['current-user'], queryFn: () => fetch('/api/users/me').then((res) => res.json()), });

const form = useForm({ initialValues: { name: '', email: '', }, });

useEffect(() => { if (query.data) { // Even if query.data changes, form will be initialized only once form.initialize(query.data); } }, [query.data]); }


----------------------------------------

TITLE: Updating SimpleGrid Breakpoints and Spacing (TSX)
DESCRIPTION: This snippet shows how to configure responsive column counts, spacing, and vertical spacing for the Mantine SimpleGrid component using the new object format. It defines different values for base, sm, and lg breakpoints.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_19

LANGUAGE: tsx
CODE:

import { SimpleGrid } from '@mantine/core';

function Demo() { return ( <SimpleGrid cols={{ base: 1, sm: 2, lg: 5 }} spacing={{ base: 10, sm: 'xl' }} verticalSpacing={{ base: 'md', sm: 'xl' }} > <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </SimpleGrid> ); }


----------------------------------------

TITLE: Importing Specific Mantine Component Styles in React with TypeScript
DESCRIPTION: Shows how to import CSS styles for individual Mantine components within a TypeScript React application. Dependencies include @mantine/core and understanding any inter-component dependencies such as UnstyledButton for Button. Only the styles for the specified components will be included, reducing bundle size. Multiple import statements can be used to target the required components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/mantine-styles.mdx#_snippet_1

LANGUAGE: TypeScript
CODE:

import '@mantine/core/styles/UnstyledButton.css'; import '@mantine/core/styles/Button.css';


----------------------------------------

TITLE: Using renderRoot with React Router NavLink (TSX)
DESCRIPTION: Shows how to integrate a Mantine `Button` with `react-router-dom`'s `NavLink`, which uses a function for its `className` prop to handle active states. The `renderRoot` prop is necessary to correctly pass props and apply conditional classes using `cx` based on `isActive`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/polymorphic.mdx#_snippet_5

LANGUAGE: tsx
CODE:

import cx from 'clsx'; import { NavLink } from 'react-router-dom'; import { Button } from '@mantine/core';

function Demo() { return ( <Button renderRoot={({ className, ...others }) => ( <NavLink className={({ isActive }) => cx(className, { 'active-class': isActive }) } {...others} /> )} > React router NavLink </Button> ); }


----------------------------------------

TITLE: Applying classNames and Styles Props to Mantine Components (TypeScript)
DESCRIPTION: This snippet demonstrates how to customize the visual appearance of Mantine's Button component using the classNames and styles props. It shows how to target inner elements via selectors, passing an object that maps element names to CSS class names or inline style objects. Dependencies: @mantine/core. Expects valid class name strings or style objects for respective selectors; these approaches enable highly specific custom styling for each sub-element of the component.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/styles-api.mdx#_snippet_0

LANGUAGE: TypeScript
CODE:

import { Button, createTheme, MantineProvider } from '@mantine/core';

function ClassNamesDemo() { return ( <Button classNames={{ root: 'my-root-class', label: 'my-label-class', inner: 'my-inner-class', }} > Button </Button> ); }

function StylesDemo() { return ( <Button styles={{ root: { backgroundColor: 'red' }, label: { color: 'blue' }, inner: { fontSize: 20 }, }} > Button </Button> ); }


----------------------------------------

TITLE: Using Custom Components as Mantine Menu.Item (TSX)
DESCRIPTION: Explains how to render a custom React component as a Menu.Item and highlights the requirement for the custom component to correctly forward refs and spread props.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/menu.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { Menu } from '@mantine/core';

// ❌ Will not work with Menu.Item function IncorrectItem() { return <button type="button">My custom Menu item</button>; }

// ✅ Will work correctly with Menu.Item const CorrectItem = forwardRef< HTMLButtonElement, React.ComponentPropsWithoutRef<'button'>

((props, ref) => ( <button type="button" {...props} ref={ref}> My custom Menu item

</button>

));

function Demo() { // ❌ Will not work const incorrect = <Menu.Item component={IncorrectItem} />;

// ✅ Will work const correct = <Menu.Item component={CorrectItem} />; }


----------------------------------------

TITLE: Initializing Mantine Form and Using isTouched/isDirty
DESCRIPTION: This code snippet initializes a Mantine form using `useForm`. It demonstrates how to use `form.isTouched` and `form.isDirty` to check the touched and dirty status of individual fields and the entire form.  Dependencies include the `@mantine/form` library.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/status.mdx#_snippet_0

LANGUAGE: tsx
CODE:
import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { a: 1, nested: { field: '' } },
});

// Provide path as first argument to get state of single field
form.isTouched('a'); // -> was field 'a' focused or changed?
form.isDirty('a'); // -> was field 'a' modified?
form.isDirty('nested.field'); // -> nested fields are also supported

// If field path is not provided,
// then functions will return form state instead
form.isTouched(); // -> was any field in form focused or changed?
form.isDirty(); // -> was any field in form modified?

----------------------------------------

TITLE: Testing Mantine Modal Close State with React Testing Library (TSX)
DESCRIPTION: This snippet shows a React Testing Library test that successfully verifies the closed state of the AuthModal component after submitting the form within it. It simulates opening the modal, typing into the input fields, clicking the submit button, and then asserts that the modal's heading is no longer present in the document using queryByRole and not.toBeInTheDocument(). This confirms the modal closes as expected upon form submission. Requires the custom render function from the snippet that disables transitions.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/portals-testing.mdx#_snippet_4

LANGUAGE: tsx
CODE:

describe('AuthModal', () => { it('closes modal after the form has been submitted', async () => { render(<AuthModal />); await userEvent.click(screen.getByRole('button', { name: 'Open authentication modal' })); await userEvent.type(screen.getByRole('textbox', { name: 'Username' }), 'john.doe'); await userEvent.type(screen.getByLabelText('Password'), 'password'); await userEvent.click(screen.getByRole('button', { name: 'Log in' })); expect(screen.queryByRole('heading', { name: 'Authenticate' })).not.toBeInTheDocument(); }); });


----------------------------------------

TITLE: Describing Polymorphic Component Types and Usage
DESCRIPTION: This snippet discusses the type inference of polymorphic components in Mantine, illustrating how component props are determined based on the 'component' prop or default element, with code examples using the Box component for different root elements.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/polymorphic-in-polymorphic.mdx#_snippet_2

LANGUAGE: TypeScript
CODE:

Polymorphic components types

Polymorphic components types are defined by the type of the root element which is not known until the component is used.

Example:

import { Box } from '@mantine/core';

// MyBox component props types are now known
// Types will be assigned only when MyBox is used
const MyBox = Box;

function Demo() {
  // MyBox props type can be determined based on
  // `component` prop or its absence
  // In this case MyBox props type contain
  // React.ComponentProps<'div'>
  return <MyBox>Hello</MyBox>;
}

function Demo2() {
  // In this case MyBox props type contain
  // React.ComponentProps<'a'>
  return <MyBox component="a" href="https://mantine.dev/" />;
}

----------------------------------------

TITLE: Input Aria-label Example
DESCRIPTION: Demonstrates the use of `aria-label` for accessibility when using the `Input` component. If an associated label isn't present, `aria-label` is necessary to provide a text alternative. Requires `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/input.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { Input } from '@mantine/core';

// ok – the input is labelled by the aria-label function WithAriaLabel() { return <Input aria-label="Your email" />; }

// ok – the input is labelled by the label element function WithLabel() { return ( <> <label htmlFor="my-email">Your email</label> <Input id="my-email" /> </> ); }


----------------------------------------

TITLE: Zod Resolver Example
DESCRIPTION: Shows how to use the `zodResolver` from `@mantine-form-zod-resolver` to integrate Zod schema validation with Mantine forms. It outlines the necessary imports, schema definition, and form initialization with validation, including example output for form errors.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-3-0.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { zodResolver } from 'mantine-form-zod-resolver'; import { z } from 'zod'; import { useForm } from '@mantine/form';

const schema = z.object({ name: z .string() .min(2, { message: 'Name should have at least 2 letters' }), email: z.string().email({ message: 'Invalid email' }), age: z.number().min(18, { message: 'You must be at least 18 to create an account', }), });

const form = useForm({ initialValues: { name: '', email: '', age: 16, }, validate: zodResolver(schema), });

form.validate(); form.errors; // -> { // name: 'Name should have at least 2 letters', // email: 'Invalid email', // age: 'You must be at least 18 to create an account' // }


----------------------------------------

TITLE: Setting Default Props with MantineThemeProvider (tsx)
DESCRIPTION: This snippet demonstrates how to define and apply default props for Mantine components using MantineThemeProvider. It uses createTheme to specify default props for the Button component (setting color to 'cyan' and variant to 'outline') and then wraps a part of the application with MantineThemeProvider to apply this theme, ensuring buttons within this scope inherit these defaults. Requires react and @mantine/core.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/default-props.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { Button, createTheme, MantineThemeProvider, } from '@mantine/core';

const theme = createTheme({ components: { Button: Button.extend({ defaultProps: { color: 'cyan', variant: 'outline', }, }), }, });

function Demo() { return ( <> <MantineThemeProvider theme={theme}> {/* Part of the app with theme */} </MantineThemeProvider>

  {/* Another part without theme */}
</>

); }


----------------------------------------

TITLE: Importing Mantine Core Styles (Native CSS) - TSX
DESCRIPTION: Shows how to import the core Mantine CSS file after the migration to native CSS, replacing the previous Emotion-based styling. This is required to get the default component styles.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-0-0.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import '@mantine/core/styles.css';


----------------------------------------

TITLE: Implementing List Valibot Schema Validation in Mantine Form (TSX)
DESCRIPTION: Shows how to use `valibotResolver` with a Valibot schema containing an array of objects to validate list items within a Mantine form.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-4-0.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver'; import { array, minLength, object, string } from 'valibot'; import { useForm } from '@mantine/form';

const listSchema = object({ list: array( object({ name: string([ minLength(2, 'Name should have at least 2 letters'), ]), }) ), });

const form = useForm({ initialValues: { list: [{ name: '' }], }, validate: valibotResolver(listSchema), });

form.validate(); form.errors; // -> { // 'list.0.name': 'Name should have at least 2 letters', // }


----------------------------------------

TITLE: Exporting Testing Utilities from Central File in TSX
DESCRIPTION: Shows how to create a central index file (`./testing-utils/index.ts`) to re-export testing utilities from `@testing-library/react`, `@testing-library/user-event`, and the custom `render` function. This approach simplifies imports in individual test files.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/jest.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import userEvent from '@testing-library/user-event';

export * from '@testing-library/react'; export { render } from './render'; export { userEvent };


----------------------------------------

TITLE: Customizing Form Touch Behavior with useForm touchTrigger Option in TypeScript React
DESCRIPTION: Shows how to configure the newly added touchTrigger option in Mantine's useForm hook to customize when form fields become 'touched'. The 'focus' option makes a field considered touched only on focus events, while 'change' (default) triggers on value change or focus. The example demonstrates form state changes and usage of getInputProps for focus handling. Requires React and @mantine/form package. Enables finer control over form validation UX.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.16.0.md#_snippet_7

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { a: 1 }, touchTrigger: 'focus', });

form.isTouched('a'); // -> false form.setFieldValue('a', 2); form.isTouched('a'); // -> false

// onFocus is called automatically when the user focuses the field form.getInputProps('a').onFocus(); form.isTouched('a'); // -> true


----------------------------------------

TITLE: Correcting compound components by adding 'use client' directive
DESCRIPTION: This snippet shows how to enable the use of Mantine's compound components in a client environment by adding `'use client'` at the top of the file.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_7

LANGUAGE: TypeScript
CODE:

// ✅ No error 'use client';

import { Popover } from '@mantine/core';

function Demo() { return ( <Popover> <Popover.Target> <button>Toggle popover</button> </Popover.Target> </Popover> ); }


----------------------------------------

TITLE: Input and Input.Wrapper id example
DESCRIPTION: Shows the correct usage of the `id` attribute when using `Input` within `Input.Wrapper`. It emphasizes the importance of setting the same `id` on both components to connect the label and input for accessibility. Requires `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/input.mdx#_snippet_4

LANGUAGE: tsx
CODE:

import { Input } from '@mantine/core';

function Demo() { return ( <Input.Wrapper label="Your email" id="your-email"> <Input id="your-email" /> </Input.Wrapper> ); }


----------------------------------------

TITLE: Defining and Using a Virtual Primary Color in Mantine (TSX)
DESCRIPTION: This snippet demonstrates how to define a virtual color named 'primary' using `virtualColor` from `@mantine/core`. It sets 'pink' as the color for the dark scheme and 'cyan' for the light scheme within the `createTheme` function. The `MantineProvider` applies this theme, and a `Box` component utilizes the 'primary' virtual color for its background, which automatically adapts based on the current light or dark color scheme.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/primary-virtual-color.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { createTheme, MantineProvider, virtualColor, Box, // Added Box import for completeness } from '@mantine/core';

const theme = createTheme({ primaryColor: 'primary',

colors: { primary: virtualColor({ name: 'primary', dark: 'pink', light: 'cyan', }), }, });

function App() { return ( <MantineProvider theme={theme}> <Box bg="primary" c="white" p="md" fw={700}> This box has virtual background color, it is pink in dark mode and cyan in light mode </Box> </MantineProvider> ); }


----------------------------------------

TITLE: Correct CSS Import Order for Mantine Overrides (TSX)
DESCRIPTION: Shows the recommended import order where importing Mantine's core styles before user styles allows user-defined styles to correctly override Mantine's default styles.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/styles-order.mdx#_snippet_1

LANGUAGE: tsx
CODE:

// ✅ Correct order – your styles override Mantine styles import '@mantine/core/styles.css'; import './styles.css';


----------------------------------------

TITLE: Handling DatePicker String Values (7.x vs 8.x)
DESCRIPTION: Compares the `onChange` callback behavior for `@mantine/dates` components between v7 and v8. In v8, callbacks receive date string values instead of `Date` objects. The example shows how to convert the string value back to a `Date` object to maintain v7 behavior.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/7x-to-8x.mdx#_snippet_4

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { DatePicker } from '@mantine/dates';

export function Demo7x() { const [value, setValue] = useState<Date | null>(null); // ⛔ 7.x – onChange is called with Date object return <DatePicker value={value} onChange={setValue} /> }


LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { DatePicker } from '@mantine/dates';

export function Demo8x() { const [value, setValue] = useState<Date | null>(null); // ✅ 8.x – onChange is called with string date value (for example '1994-08-21') // You can either // 1. Convert it to Date object to preserve old behavior // 2. Update your code to use date string values instead return <DatePicker value={value} onChange={val => setValue(new Date(val))} /> }


----------------------------------------

TITLE: Creating Components with Default Props using Mantine withProps (tsx)
DESCRIPTION: This snippet demonstrates how to use the static withProps function available on Mantine components to create new components with pre-defined default props. It shows examples creating a LinkButton from Button (setting link-specific props) and a PhoneInput from InputBase (integrating IMaskInput and setting input-specific props), illustrating how subsequent props passed to the new component override the defaults set by withProps. Requires react, @mantine/core, and react-imask.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/default-props.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { IMaskInput } from 'react-imask'; import { Button, InputBase } from '@mantine/core';

const LinkButton = Button.withProps({ component: 'a', target: '_blank', rel: 'noreferrer', variant: 'subtle', });

const PhoneInput = InputBase.withProps({ mask: '+7 (000) 000-0000', component: IMaskInput, label: 'Your phone number', placeholder: 'Your phone number', });

function Demo() { return ( <> {/* You can pass additional props to components created with withProps */} <LinkButton href="https://mantine.dev"> Mantine website </LinkButton>

  {/* Component props override default props defined in `withProps` */}
  <PhoneInput placeholder="Personal phone" />
</>

); }


----------------------------------------

TITLE: Using useDisclosure Hook with Basic Handlers in React (TypeScript)
DESCRIPTION: This snippet demonstrates how to use the useDisclosure hook from @mantine/hooks to manage a boolean state in a React component. The example initializes the state as closed (false) and provides handlers to open, close, or toggle the state for managing UI components like modals or popovers. There are no additional dependencies besides React and Mantine Hooks, and the inputs/outputs are limited to the boolean state and a handler object with open, close, and toggle functions.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-disclosure.mdx#_snippet_0

LANGUAGE: TypeScript
CODE:

import { useDisclosure } from '@mantine/hooks';

function Demo() { const [opened, handlers] = useDisclosure(false);

// Sets opened to true handlers.open();

// Sets opened to false handlers.close();

// Sets opened to true if it was false and vice versa handlers.toggle(); }


----------------------------------------

TITLE: Setting Up MantineProvider in app/layout.tsx
DESCRIPTION: Sets up MantineProvider at the root of the application with color scheme support and defines metadata for the app in the 'app' directory router.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/next.mdx#_snippet_7

LANGUAGE: TypeScript
CODE:

import '@mantine/core/styles.css';

import { ColorSchemeScript, MantineProvider, mantineHtmlProps } from '@mantine/core';

export const metadata = { title: 'My Mantine app', description: 'I have followed setup instructions carefully', };

export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en" {...mantineHtmlProps}> <head> <ColorSchemeScript /> </head> <body> <MantineProvider>{children}</MantineProvider> </body> </html> ); }


----------------------------------------

TITLE: Setting Initial Values with useForm in Mantine
DESCRIPTION: Demonstrates how to set initial values when creating a form with the useForm hook. Initial values define the starting state of the form before user interaction.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/values.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { name: '', email: '', }, });


----------------------------------------

TITLE: Error when calling extend() from server component
DESCRIPTION: This snippet shows an error caused by trying to call `Button.extend()` in a server component without the `'use client'` directive. The fix involves adding `'use client'` at the top.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_9

LANGUAGE: TypeScript
CODE:

// ❌ This will throw an error import { Button, createTheme } from '@mantine/core';

export const theme = createTheme({ components: { Button: Button.extend({}), }, });


----------------------------------------

TITLE: CloseButton Accessibility Example
DESCRIPTION: This code snippet demonstrates how to make the Mantine `CloseButton` accessible to screen readers by providing an `aria-label` or using the `VisuallyHidden` component. The example shows two approaches: directly setting the `aria-label` and wrapping the button content with the `VisuallyHidden` component to provide a text alternative for screen readers. This is important for users who rely on assistive technologies to understand the purpose of the button.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/close-button.mdx#_snippet_0

LANGUAGE: TypeScript
CODE:

import { CloseButton, VisuallyHidden } from '@mantine/core';

function Demo() { return ( <> <CloseButton aria-label="Close modal" />

  <CloseButton>
    <VisuallyHidden>Close modal</VisuallyHidden>
  </CloseButton>
</>

); }


----------------------------------------

TITLE: Updating Initial Values with Mantine form.setInitialValues TSX
DESCRIPTION: Demonstrates how to use `form.setInitialValues` and `form.setValues` to update a Mantine form's initial and current values after fetching data asynchronously, typically within a `useEffect` hook. This allows `form.reset` to revert to the fetched data and enables accurate dirty state tracking.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.1.0.md#_snippet_6

LANGUAGE: tsx
CODE:

import { useEffect } from 'react'; import { useForm } from '@mantine/form';

function Demo() { const form = useForm({ initialValues: { name: '', email: '', }, });

useEffect(() => { fetch('/api/user') .then((res) => res.json()) .then((data) => { // Update initial values after form was initialized // These values will be used in form.reset // and to compare values to get dirty state form.setInitialValues(data); form.setValues(data); }); }, []); }


----------------------------------------

TITLE: Creating and Applying Custom Theme - TSX
DESCRIPTION: Illustrates the usage of the new createTheme function to define a custom theme override object. This theme is then passed to the MantineProvider to apply custom styling across the application.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-0-0.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({ fontFamily: 'sans-serif', primaryColor: 'orange', });

function Demo() { return ( <MantineProvider theme={theme}> {/* Your app here */} </MantineProvider> ); }


----------------------------------------

TITLE: Creating and Using Form Context with Mantine
DESCRIPTION: Example showing how to create a form context using createFormContext, define a context field component, and implement the main form component with FormProvider.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/create-form-context.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { TextInput } from '@mantine/core'; import { createFormContext } from '@mantine/form';

// Definition of form values is required interface FormValues { age: number; name: string; }

// createFormContext returns a tuple with 3 items: // FormProvider is a component that sets form context // useFormContext hook return form object that was previously set in FormProvider // useForm hook works the same way as useForm exported from the package but has predefined type const [FormProvider, useFormContext, useForm] = createFormContext<FormValues>();

function ContextField() { const form = useFormContext(); return ( <TextInput label="Your name" key={form.key('name')} {...form.getInputProps('name')} /> ); }

export function Context() { // Create form as described in use-form documentation const form = useForm({ mode: 'uncontrolled', initialValues: { age: 0, name: '', }, });

// Wrap your form with FormProvider return ( <FormProvider form={form}> <form onSubmit={form.onSubmit(() => {})}> <ContextField /> </form> </FormProvider> ); }


----------------------------------------

TITLE: Getting Input DOM Node with useForm in TSX
DESCRIPTION: This snippet demonstrates how to obtain the HTML DOM node for a specific form input field using the `form.getInputNode` function provided by the Mantine `useForm` hook. It shows how to get nodes for simple paths like 'order_id' and nested paths like 'user.email'. This function is useful for direct DOM manipulation, such as focusing an element, and requires the `@mantine/form` dependency.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/focus-first-input-with-error.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { order_id: null, user: { email: '' }, }, });

// Returns input DOM node for order_id input form.getInputNode('order_id');

// Returns input DOM node for user.email input form.getInputNode('user.email');


----------------------------------------

TITLE: Displaying Mantine Notifications at Various Positions (TSX)
DESCRIPTION: Demonstrates how to use the `@mantine/notifications` package to display notifications at different positions on the screen ('top-left', 'top-right', 'bottom-left', 'bottom-right', 'top-center', 'bottom-center'). It maps through an array of positions, creating a Button for each that triggers a notification at the specified position using `notifications.show`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.12.0.md#_snippet_0

LANGUAGE: tsx
CODE:

import { Button, Group } from '@mantine/core'; import { notifications } from '@mantine/notifications';

const positions = [ 'top-left', 'top-right', 'bottom-left', 'bottom-right', 'top-center', 'bottom-center', ] as const;

function Demo() { const buttons = positions.map((position) => ( <Button key={position} onClick={() => notifications.show({ title: Notification at ${position}, message: Notification at ${position} message, position, }) } > {position} </Button> ));

return <Group>{buttons}</Group>; }


----------------------------------------

TITLE: Defining Custom Mantine Theme Colors (tsx)
DESCRIPTION: Demonstrates how to add a custom color with 10 defined shades (from lightest to darkest) to the `theme.colors` object using `createTheme`. It also shows how to set the `primaryColor` to reference this custom color and define the `primaryShade` with different indices for light and dark modes to control the default shade used in filled variants. Requires `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/ten-shades-per-color.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { createTheme } from '@mantine/core';

const theme = createTheme({ colors: { oceanBlue: [ '#7AD1DD', // lightest '#5FCCDB', '#44CADC', '#2AC9DE', '#1AC2D9', '#11B7CD', '#09ADC3', // primaryShade light '#0E99AC', '#128797', // primaryShade dark '#147885', // darkest ], },

// theme.primaryColor must be key of theme.colors object, // hex/rgb/other values are not supported primaryColor: 'oceanBlue',

// primaryShade is the index of main color in theme.colors[color] arrays // theme.colors[color][primaryShade] is used in components with filled variant primaryShade: { light: 6, dark: 8 }, });


----------------------------------------

TITLE: Validating Nested Fields with Valibot and Mantine Form in TypeScript
DESCRIPTION: Illustrates validating nested object structures using `valibotResolver`. Defines a Valibot schema with a nested `v.object` and integrates it with the `validate` option in `useForm`. Shows the resulting error structure (using dot notation for nested fields) accessed via `form.errors` after validation. Requires `mantine-form-valibot-resolver`, `valibot`, and `@mantine/form`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_13

LANGUAGE: tsx
CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver'; import * as v from 'valibot'; import { useForm } from '@mantine/form';

const nestedSchema = v.object({ nested: v.object({ field: v.pipe( v.string(), v.minLength(2, 'Field should have at least 2 letters') ), }), });

const form = useForm({ initialValues: { nested: { field: '', }, }, validate: valibotResolver(nestedSchema), });

form.validate(); form.errors; // -> { // 'nested.field': 'Field should have at least 2 letters', // }


----------------------------------------

TITLE: Controlling Mantine Popover State (TSX)
DESCRIPTION: Example showing how to manage the open/closed state of a Mantine Popover component using React's `useState` hook and the `opened` and `onChange` props. The button toggles the state.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/popover.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { Button, Popover } from '@mantine/core';

function Demo() { const [opened, setOpened] = useState(false); return ( <Popover opened={opened} onChange={setOpened}> <Popover.Target> <Button onClick={() => setOpened((o) => !o)}> Toggle popover </Button> </Popover.Target>

  <Popover.Dropdown>Dropdown</Popover.Dropdown>
</Popover>

); }


----------------------------------------

TITLE: Applying Layout Component with Metadata in JavaScript/TypeScript
DESCRIPTION: This snippet imports a 'Layout' component and exports the result of calling it with the 'meta' object defined in the same file. This pattern is commonly used in frameworks like Next.js to wrap page content with a shared layout, passing page-specific data.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/other-libs.mdx#_snippet_1

LANGUAGE: javascript
CODE:

import { Layout } from '@/layout';

export default Layout(meta);


----------------------------------------

TITLE: Creating Styled Components with @mantine/emotion Package in React
DESCRIPTION: Demonstrates how to use the createStyles function from the new @mantine/emotion package to create styled components with theme integration, responsive design, and light/dark mode support.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.9.0.md#_snippet_0

LANGUAGE: tsx
CODE:

import { rem } from '@mantine/core'; import { createStyles } from '@mantine/emotion';

const useStyles = createStyles((theme, _, u) => ({ wrapper: { maxWidth: rem(400), width: '100%', height: rem(180), display: 'flex', alignItems: 'center', justifyContent: 'center', marginLeft: 'auto', marginRight: 'auto', borderRadius: theme.radius.sm,

// Use light and dark selectors to change styles based on color scheme
[u.light]: {
  backgroundColor: theme.colors.gray[1],
},

[u.dark]: {
  backgroundColor: theme.colors.dark[5],
},

// Reference theme.breakpoints in smallerThan and largerThan functions
[u.smallerThan('sm')]: {
  // Child reference in nested selectors via ref
  [`& .${u.ref('child')}`]: {
    fontSize: theme.fontSizes.xs,
  },
},

},

child: { // Assign selector to a ref to reference it in other styles ref: u.ref('child'), padding: theme.spacing.md, borderRadius: theme.radius.sm, boxShadow: theme.shadows.md,

[u.light]: {
  backgroundColor: theme.white,
  color: theme.black,
},

[u.dark]: {
  backgroundColor: theme.colors.dark[8],
  color: theme.white,
},

}, }));

function Demo() { const { classes } = useStyles();

return ( <div className={classes.wrapper}> <div className={classes.child}>createStyles demo</div> </div> ); }


----------------------------------------

TITLE: Creating Form Context in a Separate File
DESCRIPTION: Example of creating a form context in a separate file to avoid dependency cycles, defining interface for form values and exporting the context variables.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/create-form-context.mdx#_snippet_1

LANGUAGE: tsx
CODE:

// form-context.ts file import { createFormContext } from '@mantine/form';

interface UserFormValues { age: number; name: string; }

// You can give context variables any name export const [UserFormProvider, useUserFormContext, useUserForm] = createFormContext<UserFormValues>();


----------------------------------------

TITLE: Subscribing to Mantine Notifications State with useNotifications Hook (TSX)
DESCRIPTION: Illustrates how to subscribe to and display the state of notifications using the `useNotifications` hook from `@mantine/notifications`. The component uses `useCounter` to generate unique notification titles, triggers notifications with `notifications.show`, and displays the current `notificationsStore.notifications` and `notificationsStore.queue` states within Code blocks.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.12.0.md#_snippet_1

LANGUAGE: tsx
CODE:

import { Button, Text, Code } from '@mantine/core'; import { notifications, useNotifications } from '@mantine/notifications'; import { useCounter } from '@mantine/hooks'; // Assuming useCounter is imported

function Demo() { const [counter, { increment }] = useCounter(); const notificationsStore = useNotifications();

const showNotification = () => { notifications.show({ title: Notification ${counter}, message: 'Most notifications are added to queue', });

increment();

};

return ( <> <Button onClick={showNotification} mb="md"> Show notification </Button>

  <Text>Notifications state</Text>
  <Code block>{JSON.stringify(notificationsStore.notifications, null, 2)}</Code>

  <Text mt="md">Notifications queue</Text>
  <Code block>{JSON.stringify(notificationsStore.queue, null, 2)}</Code>
</>

); }


----------------------------------------

TITLE: Using useMantineColorScheme and useComputedColorScheme for Toggling (TSX)
DESCRIPTION: Demonstrates how to use both useMantineColorScheme and useComputedColorScheme. It highlights the correct approach to toggling the color scheme by using the computed value ('light' or 'dark') from useComputedColorScheme, which avoids issues when the colorScheme state is 'auto'.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/color-schemes.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { useComputedColorScheme, useMantineColorScheme, } from '@mantine/core';

function Demo() { // -> colorScheme is 'auto' | 'light' | 'dark' const { colorScheme, setColorScheme } = useMantineColorScheme();

// -> computedColorScheme is 'light' | 'dark', argument is the default value const computedColorScheme = useComputedColorScheme('light');

// Incorrect color scheme toggle implementation // If colorScheme is 'auto', then it is not possible to // change color scheme correctly in all cases: // 'auto' can mean both light and dark const toggleColorScheme = () => { setColorScheme(colorScheme === 'dark' ? 'light' : 'dark'); };

// Correct color scheme toggle implementation // computedColorScheme is always either 'light' or 'dark' const toggleColorScheme = () => { setColorScheme(computedColorScheme === 'dark' ? 'light' : 'dark'); }; }


----------------------------------------

TITLE: Defining a Mantine Modal Component (TSX)
DESCRIPTION: This snippet defines a basic React component called AuthModal using Mantine components. It demonstrates the use of Modal, Button, TextInput, PasswordInput, and the useDisclosure hook from @mantine/hooks to manage the modal's open/closed state. The component includes a button to open the modal and a simple form inside the modal.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/portals-testing.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { Button, Modal, PasswordInput, TextInput } from '@mantine/core'; import { useDisclosure } from '@mantine/hooks';

export function AuthModal() { const [opened, { open, close }] = useDisclosure();

return ( <> <Modal title="Authenticate" opened={opened} onClose={close}> <form onSubmit={(event) => { event.preventDefault(); close(); }} > <TextInput data-autofocus label="Username" placeholder="Enter your username" /> <PasswordInput label="Password" placeholder="Enter your password" /> <Button type="submit">Log in</Button> </form> </Modal>

  <Button onClick={open}>Open authentication modal</Button>
</>

); }


----------------------------------------

TITLE: Using use-radial-move Hook in Mantine with React TypeScript
DESCRIPTION: Demonstrates how to use the new useRadialMove hook from @mantine/hooks to implement a custom radial slider component with React and Mantine. Requires @mantine/core, @mantine/hooks, and a local CSS module for styling. The hook provides a ref to attach to the root element, and updates the angle value based on user interaction, displaying the current angle using state.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.15.0.md#_snippet_0

LANGUAGE: TSX
CODE:

import { useState } from 'react'; import { Box } from '@mantine/core'; import { useRadialMove } from '@mantine/hooks'; import classes from './Demo.module.css';

function Demo() { const [value, setValue] = useState(115); const { ref } = useRadialMove(setValue);

return ( <Box className={classes.root} ref={ref} style={{ '--angle': ${value}deg }}> <div className={classes.value}>{value}°</div> <div className={classes.thumb} /> </Box> ); }


----------------------------------------

TITLE: Creating Custom Checkbox and Radio Card Components in Mantine
DESCRIPTION: This snippet presents how to replace standard checkboxes and radios with customizable card components (`Checkbox.Card` and `Radio.Card`) that support accessibility and keyboard interactions. The examples include toggle logic with React's useState hook and demonstrate grouping multiple cards within `Checkbox.Group` and `Radio.Group` with corresponding state management. These components enable building more interactive, styled selection options while maintaining accessibility standards.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.10.0.md#_snippet_4

LANGUAGE: TypeScript
CODE:

import { useState } from 'react'; import { Checkbox, Group, Text } from '@mantine/core'; import classes from './Demo.module.css';

function Demo() { const [checked, setChecked] = useState(false);

return ( <Checkbox.Card className={classes.root} radius="md" checked={checked} onClick={() => setChecked((c) => !c)} > <Group wrap="nowrap" align="flex-start"> <Checkbox.Indicator /> <div> <Text className={classes.label}>@mantine/core</Text> <Text className={classes.description}> Core components library: inputs, buttons, overlays, etc. </Text> </div> </Group> </Checkbox.Card> ); }


LANGUAGE: TypeScript
CODE:

import { useState } from 'react'; import { Checkbox, Group, Stack, Text } from '@mantine/core'; import classes from './Demo.module.css';

const data = [ { name: '@mantine/core', description: 'Core components library: inputs, buttons, overlays, etc.', }, { name: '@mantine/hooks', description: 'Collection of reusable hooks for React applications.' }, { name: '@mantine/notifications', description: 'Notifications system' }, ];

function Demo() { const [value, setValue] = useState<string[]>([]);

const cards = data.map((item) => ( <Checkbox.Card className={classes.root} radius="md" value={item.name} key={item.name}> <Group wrap="nowrap" align="flex-start"> <Checkbox.Indicator /> <div> <Text className={classes.label}>{item.name}</Text> <Text className={classes.description}>{item.description}</Text> </div> </Group> </Checkbox.Card> ));

return ( <> <Checkbox.Group value={value} onChange={setValue} label="Pick packages to install" description="Choose all packages that you will need in your application" > <Stack pt="md" gap="xs"> {cards} </Stack> </Checkbox.Group>

  <Text fz="xs" mt="md">
    CurrentValue: {value.join(', ') || '–'}
  </Text>
</>

); }


LANGUAGE: TypeScript
CODE:

import { useState } from 'react'; import { Group, Radio, Text } from '@mantine/core'; import classes from './Demo.module.css';

function Demo() { const [checked, setChecked] = useState(false);

return ( <Radio.Card className={classes.root} radius="md" checked={checked} onClick={() => setChecked((c) => !c)} > <Group wrap="nowrap" align="flex-start"> <Radio.Indicator /> <div> <Text className={classes.label}>@mantine/core</Text> <Text className={classes.description}> Core components library: inputs, buttons, overlays, etc. </Text> </div> </Group> </Radio.Card> ); }


LANGUAGE: TypeScript
CODE:

import { useState } from 'react'; import { Group, Radio, Stack, Text } from '@mantine/core'; import classes from './Demo.module.css';

const data = [ { name: '@mantine/core', description: 'Core components library: inputs, buttons, overlays, etc.', }, { name: '@mantine/hooks', description: 'Collection of reusable hooks for React applications.' }, { name: '@mantine/notifications', description: 'Notifications system' }, ];

function Demo() { const [value, setValue] = useState<string | null>(null);

const cards = data.map((item) => ( <Radio.Card className={classes.root} radius="md" value={item.name} key={item.name}> <Group wrap="nowrap" align="flex-start"> <Radio.Indicator /> <div> <Text className={classes.label}>{item.name}</Text> <Text className={classes.description}>{item.description}</Text> </div> </Group> </Radio.Card> ));

return ( <> <Radio.Group value={value} onChange={setValue} label="Pick one package to install" description="Choose a package that you will need in your application" > <Stack pt="md" gap="xs"> {cards} </Stack> </Radio.Group>

  <Text fz="xs" mt="md">
    CurrentValue: {value || '–'}
  </Text>
</>

); }


----------------------------------------

TITLE: Setting up Emotion SSR Cache in Next.js App Router (React/TypeScript)
DESCRIPTION: A client component designed to manage Emotion's server-side rendering cache in a Next.js App Router environment. It initializes an Emotion cache, intercepts style insertions during SSR, and uses `useServerInsertedHTML` to inject the collected styles into the document's head, ensuring correct styling on the initial render. This component should be created at `app/EmotionRootStyleRegistry.tsx` and requires `@emotion/cache`, `@emotion/react`, `next/navigation`, and `react`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_9

LANGUAGE: tsx
CODE:

'use client';

import { useState } from 'react'; import { useServerInsertedHTML } from 'next/navigation'; import createCache from '@emotion/cache'; import { CacheProvider } from '@emotion/react';

export function RootStyleRegistry({ children, }: { children: React.ReactNode; }) { const [{ cache, flush }] = useState(() => { const cache = createCache({ key: 'my' }); cache.compat = true; const prevInsert = cache.insert; let inserted: string[] = []; cache.insert = (...args) => { const serialized = args[1]; if (cache.inserted[serialized.name] === undefined) { inserted.push(serialized.name); } return prevInsert(...args); }; const flush = () => { const prevInserted = inserted; inserted = []; return prevInserted; }; return { cache, flush }; });

useServerInsertedHTML(() => { const names = flush(); if (names.length === 0) return null; let styles = ''; for (const name of names) { styles += cache.inserted[name]; } return ( <style data-emotion={${cache.key} ${names.join(' ')}} dangerouslySetInnerHTML={{ __html: styles, }} /> ); });

return <CacheProvider value={cache}>{children}</CacheProvider>; }


----------------------------------------

TITLE: Searching Options in Mantine MultiSelect with React Testing Library (TypeScript/TSX)
DESCRIPTION: This test sample verifies the search/filtering behavior of a Mantine MultiSelect component by simulating user typing and checking visible options. Required dependencies are Mantine's MultiSelect, React Testing Library utilities, and Jest/Vitest as the test runner. The component is rendered with the 'searchable' prop. Input involves typing a query string into the input, after opening the dropdown, and checking for the presence or absence of list options via their labels. This pattern tests the search algorithm and filter visibility in controlled components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/combobox-testing.mdx#_snippet_2

LANGUAGE: TSX
CODE:

import { MultiSelect } from '@mantine/core';

function MyForm() { return ( <MultiSelect name="groceries" searchable label="Select groceries" data=[ { value: 'banana', label: 'Banana' }, { value: 'apple', label: 'Apple' }, { value: 'orange', label: 'Orange' }, ] /> ); }

it('searches for options', () => { render(<MyForm />);

// Click Select to open the options list await userEvent.click(screen.getByRole('textbox', { name: 'Select groceries' }));

// Type search query await userEvent.type(screen.getByRole('textbox', { name: 'Select groceries' }), 'banana');

// Verify that only one option is visible expect(screen.getByRole('option', { name: 'Banana' })).toBeVisible(); expect(screen.queryByRole('option', { name: 'Apple' })).toBeNull(); expect(screen.queryByRole('option', { name: 'Orange' })).toBeNull(); });


----------------------------------------

TITLE: Handling List Items in Form State - Mantine (TypeScript/TSX)
DESCRIPTION: This code block describes various operations for managing array fields within a form using useForm, including adding, removing, replacing, and reordering list items. All methods operate on field paths that point to arrays in the form state. Valid inputs include item objects and index positions as required by each method; these affect the current form state mutation and should correspond to existing field definitions.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_2

LANGUAGE: TSX
CODE:

// Inserts given list item at the specified path form.insertListItem('fruits', { name: 'Apple', available: true });

// An optional index may be provided to specify the position in a nested field. // If the index is provided, item will be inserted at the given position. // If the index is larger than the current list, the element is inserted at the last position. form.insertListItem('fruits', { name: 'Orange', available: true }, 1);

// Removes the list item at the specified path and index. form.removeListItem('fruits', 1);

// Replaces the list item at the specified path and index with the given item. form.replaceListItem('fruits', 1, { name: 'Apple', available: true });

// Swaps two items of the list at the specified path. // You should make sure that there are elements at at the from and to index. form.reorderListItem('fruits', { from: 1, to: 0 });


----------------------------------------

TITLE: Setting aria-label on clear button with clearButtonProps
DESCRIPTION: This example illustrates adding accessible attributes to the clear button, such as 'aria-label', ensuring screen readers can communicate the button's purpose properly. Note that 'clearButtonProps' is required if 'clearable' is true.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tags-input.mdx#_snippet_28

LANGUAGE: TypeScript
CODE:

import { TagsInput } from '@mantine/core';

function Demo() { return ( <TagsInput data={[]} clearable clearButtonProps={{ 'aria-label': 'Clear input', }} /> ); }


----------------------------------------

TITLE: Referencing Mantine Theme Tokens with Style Props (TSX)
DESCRIPTION: Illustrates using Mantine's style props like `bg="red.5"` and `mt="xl"` as shorthands to reference theme values (`theme.colors.red[5]`, `theme.spacing.xl`) in React components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/styles-overview.mdx#_snippet_8

LANGUAGE: tsx
CODE:

import { Box } from '@mantine/core';

function Demo() { // bg="red.5" references theme.colors.red[5] // "red.5" is a shorthand for var(--mantine-color-red-5)

// mt="xl" references theme.spacing.xl // "xl" is a shorthand for var(--mantine-spacing-xl) return ( <Box bg="red.5" mt="xl"> My box </Box> ); }


----------------------------------------

TITLE: Referencing Mantine Theme Tokens with Style Prop (TSX)
DESCRIPTION: Shows two ways to apply styles using the `style` prop: directly with CSS variables (`var(--mantine-spacing-xl)`) and using a function that receives the `theme` object (`theme.spacing.xl`).
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/styles-overview.mdx#_snippet_9

LANGUAGE: tsx
CODE:

import { Box } from '@mantine/core';

function Demo() { return ( <> <Box style={{ margin: 'var(--mantine-spacing-xl)', color: 'var(--mantine-color-orange-5)', }} > With CSS variables </Box>

  <Box
    style={(theme) => ({
      margin: theme.spacing.xl,
      color: theme.colors.orange[5],
    })}
  >
    With theme object
  </Box>
</>

); }


----------------------------------------

TITLE: Correct Implementation of Notifications Component as Sibling in React
DESCRIPTION: This snippet demonstrates the proper way to include the Notifications component in a Mantine React application. Instead of wrapping the entire app, Notifications is rendered as a sibling element to the main application component, ensuring it functions correctly without blocking rendering. This approach aligns with the component's design constraints.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/notifications-empty-screen.mdx#_snippet_1

LANGUAGE: TypeScript
CODE:

import { MantineProvider } from '@mantine/core'; import { Notifications } from '@mantine/notifications';

function Demo() { return ( <MantineProvider> <Notifications /> <App /> </MantineProvider> ); }


----------------------------------------

TITLE: Configuring Responsive AppShell Navbar Width in React (TSX)
DESCRIPTION: Demonstrates configuring a responsive width for the `AppShell.Navbar` using an object for the `navbar.width` prop. The keys define breakpoints (`sm`, `lg`), and values set the width for viewports larger than or equal to that breakpoint. Below the main `navbar.breakpoint` ('sm' in this case), the width is 100%. Requires `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { AppShell } from '@mantine/core';

// Width is an object with breakpoints: // - width is 100% when viewport width is < theme.breakpoints.sm // - width is 200 when viewport width is >= theme.breakpoints.sm and < theme.breakpoints.lg // - width is 300 when viewport width is >= theme.breakpoints.lg function Demo() { return ( <AppShell navbar={{ width: { sm: 200, lg: 300 }, breakpoint: 'sm' }} > <AppShell.Navbar>Navbar</AppShell.Navbar> </AppShell> ); }


----------------------------------------

TITLE: Combining useFocusTrap with Other Ref Hooks in React TypeScript
DESCRIPTION: This snippet shows how to merge the ref returned by useFocusTrap with other ref hooks such as useClickOutside and useMergedRef. The useMergedRef hook combines multiple refs into a single ref callback, enabling multiple behaviors to be attached to the same DOM node. This is essential for integrating focus trapping with outside click detection or other ref based logic.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-focus-trap.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { useRef } from 'react'; import { useClickOutside, useFocusTrap, useMergedRef, } from '@mantine/hooks';

function Demo() { const myRef = useRef(); const useClickOutsideRef = useClickOutside(() => {}); const focusTrapRef = useFocusTrap(); const mergedRef = useMergedRef( myRef, useClickOutsideRef, focusTrapRef );

return <div ref={mergedRef} />; }


----------------------------------------

TITLE: Tracking Scroll Position with use-scroll-spy Hook in TypeScript React
DESCRIPTION: Demonstrates how to use the use-scroll-spy hook from Mantine to track the scroll position of heading elements in the DOM and return the index of the element currently visible in the viewport. Useful for creating interactive table of contents or navigation menus. Requires React and @mantine/hooks package. The hook accepts a CSS selector to identify headings, and outputs data with heading details and the active index. The example dynamically renders a scrollable list highlighting the active heading, with clickable buttons that scroll the corresponding element into view.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.16.0.md#_snippet_0

LANGUAGE: tsx
CODE:

import { Text, UnstyledButton } from '@mantine/core'; import { useScrollSpy } from '@mantine/hooks';

function Demo() { const spy = useScrollSpy({ selector: '#mdx :is(h1, h2, h3, h4, h5, h6)', });

const headings = spy.data.map((heading, index) => ( <li key={heading.id} style={{ listStylePosition: 'inside', paddingInlineStart: heading.depth * 20, background: index === spy.active ? 'var(--mantine-color-blue-light)' : undefined, }} > <UnstyledButton onClick={() => heading.getNode().scrollIntoView()}> {heading.value} </UnstyledButton> </li> ));

return ( <div> <Text>Scroll to heading:</Text> <ul style={{ margin: 0, padding: 0 }}>{headings}</ul> </div> ); }


----------------------------------------

TITLE: Using Custom Render and Utilities in Jest Test in TSX
DESCRIPTION: Demonstrates a typical Jest test file structure using the custom `render` function and other utilities imported from the central `../test-utils` module. Shows how to render a component and use `screen` along with `@testing-library/jest-dom` matchers for making assertions.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/jest.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { render, screen } from '../test-utils'; import { Welcome } from './Welcome';

describe('Welcome component', () => { it('has correct Next.js theming section link', () => { render(<Welcome />); expect(screen.getByText('this guide')).toHaveAttribute( 'href', 'https://mantine.dev/guides/next/' ); }); });


----------------------------------------

TITLE: Styling Mantine Components with Utility CSS via `classNames` (TSX)
DESCRIPTION: Example of applying utility CSS classes (like Tailwind CSS) to specific inner elements of a Mantine `TextInput` component using the `classNames` prop. This allows targeted styling of component parts (`root`, `input`) without relying solely on CSS Modules.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-modules.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { TextInput } from '@mantine/core';

function Demo() { return ( <TextInput classNames={{ root: 'mt-4', input: 'bg-red-500 text-white', }} /> ); }


----------------------------------------

TITLE: useMantineColorScheme Hook Signature (TSX)
DESCRIPTION: This snippet shows the type definition for the useMantineColorScheme hook, detailing the colorScheme state and the setColorScheme, toggleColorScheme, and clearColorScheme functions available for managing the color scheme.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/color-schemes.mdx#_snippet_1

LANGUAGE: tsx
CODE:

function useMantineColorScheme(): { /** Current color scheme value */ colorScheme: 'dark' | 'light' | 'auto';

/** Sets colors scheme to given value */ setColorScheme: (colorScheme: 'dark' | 'light' | 'auto') => void;

/** Toggle color scheme to the opposite value, if value is 'auto', color scheme is inferred from the OS settings */ toggleColorScheme: () => void;

/** Clears color scheme value from storage and sets it to defaultColorScheme */ clearColorScheme: () => void; };


----------------------------------------

TITLE: Configuring System Color Scheme with MantineProvider
DESCRIPTION: Shows how to enable system color scheme support in Mantine v7 by setting the `defaultColorScheme` prop to 'auto' on both `ColorSchemeScript` and `MantineProvider`. This allows components to respect the user's OS color scheme preference.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_1

LANGUAGE: tsx
CODE:

import { ColorSchemeScript, MantineProvider } from '@mantine/core';

function Demo() { return ( <> <ColorSchemeScript defaultColorScheme="auto" /> <MantineProvider defaultColorScheme="auto"> <App /> </MantineProvider> </> ); }


----------------------------------------

TITLE: Initializing Mantine useForm with Name (TSX)
DESCRIPTION: This snippet demonstrates how to initialize the `@mantine/form` hook with a `name` property. Setting a name is required to enable the use of form actions, allowing external components to modify the form state. It also shows defining an interface for the form values.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-2-0.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

export interface DemoFormValues { name: string; age: number; }

function Demo() { const form = useForm<DemoFormValues>({ name: 'demo-form', initialValues: { name: '', age: 0, }, }); }


----------------------------------------

TITLE: Fixed Next.js Layout with Mantine mantineHtmlProps
DESCRIPTION: This updated Next.js `app/layout.tsx` file demonstrates the recommended fix for the hydration warning. It involves spreading `mantineHtmlProps` onto the `<html>` element, which includes `suppressHydrationWarning` and a default `data-mantine-color-scheme` attribute.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/color-scheme-hydration-warning.mdx#_snippet_2

LANGUAGE: tsx
CODE:

// app/layout.tsx import { ColorSchemeScript, MantineProvider, mantineHtmlProps } from '@mantine/core';

export default function RootLayout({ children }: { children: any }) { return ( <html lang="en" {...mantineHtmlProps}> <head> <ColorSchemeScript /> <link rel="shortcut icon" href="/favicon.svg" /> <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, user-scalable=no" /> </head> <body> <MantineProvider>{children}</MantineProvider> </body> </html> ); }


----------------------------------------

TITLE: Using the useId Hook in React Components - Mantine - TypeScript
DESCRIPTION: This snippet demonstrates how to import and use the useId hook from @mantine/hooks within a functional React component to ensure that an input and its label share a unique, persistent identifier. As a dependency, @mantine/hooks must be installed. The Input component accepts an optional id prop; if provided, useId will use that value as the ID, otherwise it will generate a random ID that is stable across renders. The outputs are input-label pairs with matching ids, either user-specified or auto-generated. This implementation is useful for improving accessibility by binding labels to inputs, and is compatible with React and TypeScript projects.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-id.mdx#_snippet_0

LANGUAGE: TSX
CODE:

import { useId } from '@mantine/hooks';

function Input({ id }: { id?: string }) { const uuid = useId(id);

return ( <> <label htmlFor={uuid}>Input label</label> <input type="text" id={uuid} /> </> ); }

// input and label will have id 'my-id' const withId = <Input id="my-id" />;

// input and label will have random id 'mantine-fZMoF' const withoutId = <Input />;


----------------------------------------

TITLE: Referencing Theme Spacing and Colors in Style Props (TypeScript TSX)
DESCRIPTION: Illustrates using Mantine's Box component with style props that reference theme values for spacing (such as 'mt' for margin-top) and colors (props like 'c', 'bd', 'bg'). This snippet shows how to use both string values (e.g. 'xs', '-md', 'auto', '5rem') and number values for spacing, as well as referencing color tokens from the theme or raw color strings. Requires @mantine/core and Mantine theme context. Inputs include any valid string, token, or color value, and outputs the corresponding CSS on the root element. Some values depend on the current theme's color scheme.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/style-props.mdx#_snippet_1

LANGUAGE: TSX
CODE:

import { Box } from '@mantine/core';

function Demo() { return ( <> {/* margin-top: theme.spacing.xs */} <Box mt="xs" />

  {/* margin-top: theme.spacing.md * -1 */}
  <Box mt="-md" />

  {/* margin-top: auto */}
  <Box mt="auto" />

  {/* margin-top: 1rem */}
  <Box mt={16} />

  {/* margin-top: 5rem */}
  <Box mt="5rem" />
</>

); }


----------------------------------------

TITLE: Styling Mantine Slider with Emotion/styled TSX
DESCRIPTION: Shows how to wrap a Mantine `Slider` component with `@emotion/styled` to create a styled component. Styles are applied to inner elements like the slider bar and thumb using static selectors within the tagged template literal, demonstrating how CSS-in-JS can be combined with Mantine's internal structure. Requires `@emotion/styled` and `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/third-party-styles.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import styled from '@emotion/styled'; import { Slider } from '@mantine/core';

const StyledSlider = styled(Slider)` & .mantine-Slider-bar { background-color: var(--mantine-color-pink-5); }

& .mantine-Slider-thumb { border-color: var(--mantine-color-pink-5); background-color: white; width: 1.5rem; height: 1.5rem; } `;

function Demo() { return <StyledSlider defaultValue={40} />; }


----------------------------------------

TITLE: Styling Mantine Components with Styled-Components (`@emotion/styled`) (TSX)
DESCRIPTION: Illustrates creating a styled version of a Mantine `Slider` component using `@emotion/styled`. It applies styles to the root element via the styled-component wrapper and styles inner elements (`.mantine-Slider-bar`, `.mantine-Slider-thumb`) using nested static selectors targeting Mantine's internal class names. Uses Mantine CSS variables for theming.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-modules.mdx#_snippet_8

LANGUAGE: tsx
CODE:

import styled from '@emotion/styled'; import { Slider } from '@mantine/core';

const StyledSlider = styled(Slider)` & .mantine-Slider-bar { background-color: var(--mantine-color-pink-5); }

& .mantine-Slider-thumb { border-color: var(--mantine-color-pink-5); background-color: white; width: 1.5rem; height: 1.5rem; } `;

function Demo() { return <StyledSlider defaultValue={40} />; }


----------------------------------------

TITLE: Using HeadlessMantineProvider in a React Application
DESCRIPTION: Demonstrates how to import and use `HeadlessMantineProvider` to enable headless UI features in a React app, replacing the default `MantineProvider`. Wrapping the application within `HeadlessMantineProvider` disables all styling features, allowing for custom styling.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/unstyled.mdx#_snippet_0

LANGUAGE: typescript
CODE:

import { HeadlessMantineProvider } from '@mantine/core';

function App() { return ( <HeadlessMantineProvider> {/* Your application */} </HeadlessMantineProvider> ); }


----------------------------------------

TITLE: Validating Numeric Range with Mantine Form isInRange Validator in TypeScript
DESCRIPTION: This example uses the isInRange validator to ensure a numeric form field's value lies within specified minimum and/or maximum bounds. If the value is not a number, validation fails. The form manages three fields with different range constraints, validating with customized error messages. useForm hook manages form state and validation in uncontrolled mode.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validators.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { isInRange, useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { maxRange: 0, minRange: 0, minMaxRange: 0, },

validate: { maxRange: isInRange({ max: 20 }, 'Value must be 20 or less'), minRange: isInRange({ min: 10 }, 'Value must be 10 or more'), minMaxRange: isInRange( { min: 10, max: 20 }, 'Value must be between 10 and 20' ), }, });


----------------------------------------

TITLE: Using useDisclosure Hook with onOpen and onClose Callbacks in React (TypeScript)
DESCRIPTION: This example expands on the useDisclosure usage by including the onOpen and onClose callback options, which execute custom logic (such as logging) when the state changes. The hook is initialized with callbacks and demonstrates how open and close handlers invoke these functions on state transitions. Inputs include the initial state and optional callbacks; outputs are the state and handler object. React and Mantine Hooks are required dependencies.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-disclosure.mdx#_snippet_1

LANGUAGE: TypeScript
CODE:

import { useDisclosure } from '@mantine/hooks';

function Demo() { const [opened, handlers] = useDisclosure(false, { onOpen: () => console.log('Opened'), onClose: () => console.log('Closed'), });

// Calls onOpen callback and sets opened to true handlers.open();

// Does nothing, opened is already true handlers.open();

// Calls onClose callback and sets opened to false handlers.close();

// Does nothing, opened is already false handlers.close();

// Calls onOpen or onClose depending on next state handlers.toggle(); }


----------------------------------------

TITLE: Modal Accessibility Configuration
DESCRIPTION: Demonstrates how to set the accessibility props of the Modal component. It shows how to set `title` props for accessibility and to configure the aria-label for the close button, enhancing the accessibility of the modal.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/modal.mdx#_snippet_5

LANGUAGE: TypeScript
CODE:

import { Modal } from '@mantine/core';

function Demo() { return <Modal title="Modal label" opened onClose={() => {}} />; }


LANGUAGE: TypeScript
CODE:

import { Modal } from '@mantine/core';

function Demo() { return ( <Modal closeButtonProps={{ 'aria-label': 'Close modal' }} opened onClose={() => {}} /> ); }


----------------------------------------

TITLE: Implementing a Custom Tree Component with Iconography in React and Mantine
DESCRIPTION: This snippet defines a Tree component with custom icons for files and folders, utilizing Mantine core and tabler icons. The `FileIcon` function determines appropriate icons based on filename extensions and folder state, while the `Leaf` component renders individual nodes with these icons. The `Demo` component displays the Tree with specified data, allowing node selection and expansion behavior.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.10.0.md#_snippet_0

LANGUAGE: TypeScript
CODE:

import { IconFolder, IconFolderOpen } from '@tabler/icons-react'; import { Group, RenderTreeNodePayload, Tree } from '@mantine/core'; import { CssIcon, NpmIcon, TypeScriptCircleIcon } from '@mantinex/dev-icons'; import { data, dataCode } from './data'; import classes from './Demo.module.css';

interface FileIconProps { name: string; isFolder: boolean; expanded: boolean; }

function FileIcon({ name, isFolder, expanded }: FileIconProps) { if (name.endsWith('package.json')) { return <NpmIcon size={14} />; }

if (name.endsWith('.ts') || name.endsWith('.tsx') || name.endsWith('tsconfig.json')) { return <TypeScriptCircleIcon size={14} />; }

if (name.endsWith('.css')) { return <CssIcon size={14} />; }

if (isFolder) { return expanded ? ( <IconFolderOpen color="var(--mantine-color-yellow-9)" size={14} stroke={2.5} /> ) : ( <IconFolder color="var(--mantine-color-yellow-9)" size={14} stroke={2.5} /> ); }

return null; }

function Leaf({ node, expanded, hasChildren, elementProps }: RenderTreeNodePayload) { return ( <Group gap={5} {...elementProps}> <FileIcon name={node.value} isFolder={hasChildren} expanded={expanded} /> <span>{node.label}</span> </Group> ); }

function Demo() { return ( <Tree classNames={classes} selectOnClick clearSelectionOnOutsideClick data={data} renderNode={(payload) => <Leaf {...payload} />} /> ); }


----------------------------------------

TITLE: Initializing Button and Input Components with Mantine withProps Static Function in TypeScript
DESCRIPTION: Demonstrates how to use Mantine's withProps static function to create prefixed component wrappers with default props set for Button and InputBase components in a React and TypeScript project. This snippet shows setting additional static props such as HTML attributes and external input mask integration for input formatting. It includes a functional React component illustrating default props usage and overriding behavior. Dependencies include '@mantine/core' and 'react-imask'. Inputs are JSX props for components, outputs are rendered button and masked input elements with defined defaults.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-11-0.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { IMaskInput } from 'react-imask'; import { Button, InputBase } from '@mantine/core';

const LinkButton = Button.withProps({ component: 'a', target: '_blank', rel: 'noreferrer', variant: 'subtle', });

const PhoneInput = InputBase.withProps({ mask: '+7 (000) 000-0000', component: IMaskInput, label: 'Your phone number', placeholder: 'Your phone number', });

function Demo() { return ( <> {/* You can pass additional props to components created with withProps */} <LinkButton href="https://mantine.dev"> Mantine website </LinkButton>

  {/* Component props override default props defined in `withProps` */}
  <PhoneInput placeholder="Personal phone" />
</>

); }


----------------------------------------

TITLE: Notification Accessibility with aria-label in TypeScript
DESCRIPTION: This snippet demonstrates how to enhance the accessibility of the Mantine Notification component by setting the `aria-label` attribute for the close button. This allows screen readers to properly announce the purpose of the close button to users with disabilities. The `closeButtonProps` prop is used to pass accessibility attributes to the close button element.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/notification.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { Notification } from '@mantine/core';

function Demo() { return ( <Notification closeButtonProps={{ 'aria-label': 'Hide notification' }} /> ); }


----------------------------------------

TITLE: Integrating Custom Input with Mantine Form getInputProps (TypeScript)
DESCRIPTION: This snippet shows how to integrate the `CustomInput` component with `form.getInputProps`. By spreading the object returned by `form.getInputProps` onto the `CustomInput` component, all necessary form-related props (`value`, `onChange`, `error`, etc.) are automatically passed, enabling seamless form management.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/get-input-props.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form'; import { CustomInput } from './CustomInput';

function Demo() { const form = useForm({ mode: 'uncontrolled', initialValues: { name: '' }, });

return ( <CustomInput {...form.getInputProps('name')} key={form.key('name')} /> ); }


----------------------------------------

TITLE: Radio Accessibility Implementation Examples in Mantine
DESCRIPTION: Illustrates proper and improper ways to make Radio components accessible. Demonstrates using aria-label and label props to ensure screen readers can properly identify the radio inputs.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/radio.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { Radio } from '@mantine/core';

// Not ok, input is not labeled function Bad() { return <Radio />; }

// Ok, input is labelled by aria-label function GoodAriaLabel() { return <Radio aria-label="My radio" />; }

// Ok, input is labelled by label element function GoodLabel() { return <Radio label="My radio" />; }


----------------------------------------

TITLE: Making PinInput Accessible with ARIA Labels in React
DESCRIPTION: Shows how to implement accessibility for PinInput components by adding the aria-label attribute. This ensures screen readers can properly identify the purpose of the input field.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/pin-input.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { PinInput } from '@mantine/core';

function Accessibility() { return <PinInput aria-label="One time code" />; }


----------------------------------------

TITLE: Retrieving Form Values in Uncontrolled Mode with Mantine useForm
DESCRIPTION: Demonstrates initializing the `useForm` hook in `uncontrolled` mode and shows how to retrieve the current form values at any time using the `form.getValues()` method. Unlike `form.values` in this mode, `form.getValues()` always returns the latest state, even after updates via methods like `setValues`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-8-0.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { name: 'John Doe' }, });

form.getValues(); // { name: 'John Doe' }

form.setValues({ name: 'John Smith' }); form.getValues(); // { name: 'John Smith' }


----------------------------------------

TITLE: Setting Custom Font Family with System Fallback in Mantine Theme (TypeScript)
DESCRIPTION: This example shows how to define a custom font family while retaining Mantine's default system fonts as a fallback. It uses `DEFAULT_THEME.fontFamily` to append system fonts to a custom font stack, ensuring broader compatibility.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { createTheme, DEFAULT_THEME } from '@mantine/core';

const theme = createTheme({ fontFamily: Roboto, ${DEFAULT_THEME.fontFamily}, });


----------------------------------------

TITLE: Defining CSS Layer Order (SCSS)
DESCRIPTION: Illustrates how to define the order of CSS layers using the @layer directive in SCSS. This allows explicit control over cascade precedence when combining styles from different libraries or sources, ensuring Mantine styles are placed correctly within the cascade.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.1.0.md#_snippet_2

LANGUAGE: scss
CODE:

@layer base, mantine, components;


----------------------------------------

TITLE: Fetching Data with useFetch Hook
DESCRIPTION: This TypeScript code provides an example of how to use the `useFetch` hook to fetch data from an API. It demonstrates handling loading states, errors, and displaying the fetched data. Dependencies include `@mantine/core` and `@mantine/hooks`. It uses the `LoadingOverlay` component to indicate loading and the `error` state to display error messages.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.8.0.md#_snippet_6

LANGUAGE: TypeScript
CODE:

import { Box, Button, Code, Group, LoadingOverlay, Text } from '@mantine/core'; import { useFetch } from '@mantine/hooks';

interface Item { userId: number; id: number; title: string; completed: boolean; }

function Demo() { const { data, loading, error, refetch, abort } = useFetch<Item[]>( 'https://jsonplaceholder.typicode.com/todos/' );

return ( <div> {error && <Text c="red">{error.message}</Text>}

  <Group>
    <Button onClick={refetch} color="blue">
      Refetch
    </Button>
    <Button onClick={abort} color="red">
      Abort
    </Button>
  </Group>
  <Box pos="relative" mt="md">
    <Code block>{data ? JSON.stringify(data.slice(0, 3), null, 2) : 'Fetching'}</Code>
    <LoadingOverlay visible={loading} />
  </Box>
</div>

); }


----------------------------------------

TITLE: Defining Custom Mantine Colors in TSX Theme
DESCRIPTION: This TypeScript React snippet demonstrates how to define a new custom color palette within the Mantine theme using `createTheme`. The `colors` property accepts an object where each key is a color name and its value is an array of 10 hex color shades, from darkest to lightest.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_19

LANGUAGE: tsx
CODE:

import { createTheme } from '@mantine/core';

const theme = createTheme({ colors: { demo: [ '#FF0000', '#FF3333', '#FF6666', '#FF9999', '#FFCCCC', '#FFEEEE', '#FFFAFA', '#FFF5F5', '#FFF0F0', '#FFEBEB', ], }, });


----------------------------------------

TITLE: Configuring PostCSS with postcss-preset-mantine and postcss-simple-vars (JS)
DESCRIPTION: Creates a `postcss.config.cjs` file to configure PostCSS plugins. It includes `postcss-preset-mantine` for Mantine-specific styles and `postcss-simple-vars` to define custom variables, such as Mantine breakpoints.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/getting-started.mdx#_snippet_0

LANGUAGE: JavaScript
CODE:

module.exports = { plugins: { 'postcss-preset-mantine': {}, 'postcss-simple-vars': { variables: { 'mantine-breakpoint-xs': '36em', 'mantine-breakpoint-sm': '48em', 'mantine-breakpoint-md': '62em', 'mantine-breakpoint-lg': '75em', 'mantine-breakpoint-xl': '88em' } } } };


----------------------------------------

TITLE: Mantine Tabs with VisuallyHidden
DESCRIPTION: Shows how to use aria-label and VisuallyHidden component for accessibility purposes when a Tabs.Tab component does not contain text content. If Tabs.Tab only contains an icon, `aria-label` should be set directly or a `VisuallyHidden` component should be used to provide a label for screen readers.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tabs.mdx#_snippet_6

LANGUAGE: typescript
CODE:

import { IconCoin } from '@tabler/icons-react'; import { Tabs, VisuallyHidden } from '@mantine/core';

function Demo() { return ( <Tabs defaultValue="chat"> <Tabs.List> {/* aria-label is not required, tab is labelled by children */} <Tabs.Tab value="chat">Chat</Tabs.Tab>

    {/* aria-label is required, tab is not labelled by children */}
    <Tabs.Tab
      value="money"
      aria-label="Get money"
      leftSection={<IconCoin size={14} />}
    />

    {/* You can use VisuallyHidden instead of aria-label */}
    <Tabs.Tab value="money" leftSection={<IconCoin size={14} />}>
      <VisuallyHidden>Get money</VisuallyHidden>
    </Tabs.Tab>
  </Tabs.List>
</Tabs>

); }


----------------------------------------

TITLE: Creating a Controlled Mantine RichTextEditor Component (TSX)
DESCRIPTION: Demonstrates how to create a controlled version of the Mantine RichTextEditor component by wrapping it and managing the editor state using the `useEditor` hook from `@tiptap/react` and handling value changes via the `onChange` prop. This allows external control over the editor's content.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/tiptap.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { useEditor } from '@tiptap/react'; import StarterKit from '@tiptap/starter-kit'; import { RichTextEditor as MantineRichTextEditor } from '@mantine/tiptap';

interface RichTextEditorProps { value: string; onChange: (value: string) => void; }

export function RichTextEditor({ value, onChange, }: RichTextEditorProps) { const editor = useEditor({ extensions: [StarterKit], content: value, onUpdate: ({ editor }) => { onChange(editor.getHTML()); }, });

return ( <MantineRichTextEditor editor={editor}> <MantineRichTextEditor.Toolbar> <MantineRichTextEditor.ControlsGroup> <MantineRichTextEditor.Bold /> <MantineRichTextEditor.Italic /> </MantineRichTextEditor.ControlsGroup> </MantineRichTextEditor.Toolbar>

  <MantineRichTextEditor.Content />
</MantineRichTextEditor>

); }


----------------------------------------

TITLE: Applying Utility Classes to Mantine TextInput with TSX
DESCRIPTION: Shows how to use the `classNames` prop on a Mantine `TextInput` component to apply utility CSS classes. It specifically targets the `root` and `input` parts of the component to add margin-top, background color, and text color, illustrating integration with libraries like Tailwind CSS. Requires `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/third-party-styles.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { TextInput } from '@mantine/core';

function Demo() { return ( <TextInput classNames={{ root: 'mt-4', input: 'bg-red-500 text-white', }} /> ); }


----------------------------------------

TITLE: Controlled Checkbox Example (React)
DESCRIPTION: This example demonstrates how to create a controlled Checkbox component in React using the `useState` hook to manage the checked state. The `onChange` event updates the state, allowing for external control of the checkbox's value. The component relies on imports from `@mantine/core` and `react`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/checkbox.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { Checkbox } from '@mantine/core';

function Demo() { const [checked, setChecked] = useState(false); return ( <Checkbox checked={checked} onChange={(event) => setChecked(event.currentTarget.checked)} /> ); }


----------------------------------------

TITLE: Mantine Theme Interface Definition (TypeScript)
DESCRIPTION: This TypeScript interface defines the shape of the Mantine theme object. It includes properties for controlling focus rings, scaling, colors, fonts, spacing, breakpoints, shadows, and other visual aspects of the application.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/theme-object.mdx#_snippet_2

LANGUAGE: tsx
CODE:

interface MantineTheme { /** Controls focus ring styles. Supports the following options:

    • auto – focus ring is displayed only when the user navigates with keyboard (default value)
    • always – focus ring is displayed when the user navigates with keyboard and mouse
    • never – focus ring is always hidden (not recommended) */ focusRing: 'auto' | 'always' | 'never';

/** rem units scale, change if you customize font-size of <html /> element

  • default value is 1 (for 100%/16px font-size on <html />) */ scale: number;

/** Determines whether font-smoothing property should be set on the body, true by default */ fontSmoothing: boolean;

/** White color */ white: string;

/** Black color */ black: string;

/** Object of colors, key is color name, value is an array of at least 10 strings (colors) */ colors: MantineThemeColors;

/** Index of theme.colors[color].

  • Primary shade is used in all components to determine which color from theme.colors[color] should be used.
  • Can be either a number (0–9) or an object to specify different color shades for light and dark color schemes.
  • Default value { light: 6, dark: 8 }
  • For example,
  • { primaryShade: 6 } // shade 6 is used both for dark and light color schemes
  • { primaryShade: { light: 6, dark: 7 } } // different shades for dark and light color schemes
  • */ primaryShade: MantineColorShade | MantinePrimaryShade;

/** Key of theme.colors, hex/rgb/hsl values are not supported.

  • Determines which color will be used in all components by default.
  • Default value – blue.
  • */ primaryColor: string;

/** Function to resolve colors based on variant.

  • Can be used to deeply customize how colors are applied to Button, ActionIcon, ThemeIcon
  • and other components that use colors from theme.
  • */ variantColorResolver: VariantColorsResolver;

/** Determines whether text color must be changed based on the given color prop in filled variant

  • For example, if you pass color="blue.1" to Button component, text color will be changed to var(--mantine-color-black)
  • Default value – false
  • */ autoContrast: boolean;

/** Determines which luminance value is used to determine if text color should be light or dark.

  • Used only if theme.autoContrast is set to true.
  • Default value is 0.3
  • */ luminanceThreshold: number;

/** font-family used in all components, system fonts by default */ fontFamily: string;

/** Monospace font-family, used in code and other similar components, system fonts by default */ fontFamilyMonospace: string;

/** Controls various styles of h1-h6 elements, used in TypographyStylesProvider and Title components */ headings: { fontFamily: string; fontWeight: string; textWrap: 'wrap' | 'nowrap' | 'balance' | 'pretty' | 'stable'; sizes: { h1: HeadingStyle; h2: HeadingStyle; h3: HeadingStyle; h4: HeadingStyle; h5: HeadingStyle; h6: HeadingStyle; }; };

/** Object of values that are used to set border-radius in all components that support it */ radius: MantineRadiusValues;

/** Key of theme.radius or any valid CSS value. Default border-radius used by most components */ defaultRadius: MantineRadius;

/** Object of values that are used to set various CSS properties that control spacing between elements */ spacing: MantineSpacingValues;

/** Object of values that are used to control font-size property in all components */ fontSizes: MantineFontSizesValues;

/** Object of values that are used to control line-height property in Text component */ lineHeights: MantineLineHeightValues;

/** Object of values that are used to control breakpoints in all components,

  • values are expected to be defined in em
  • */ breakpoints: MantineBreakpointsValues;

/** Object of values that are used to add box-shadow styles to components that support shadow prop */ shadows: MantineShadowsValues;

/** Determines whether user OS settings to reduce motion should be respected, false by default */ respectReducedMotion: boolean;

/** Determines which cursor type will be used for interactive elements

    • default – cursor that is used by native HTML elements, for example, input[type="checkbox"] has cursor: default styles
    • pointer – sets cursor: pointer on interactive elements that do not have these styles by default */ cursorType: 'default' | 'pointer';

/** Default gradient configuration for components that support variant="gradient" */ defaultGradient: MantineGradient;

/** Class added to the elements that have active styles, for example, Button and ActionIcon */ activeClassName: string; }


----------------------------------------

TITLE: Implementing Container Queries in Mantine's SimpleGrid for Responsive Layouts
DESCRIPTION: This snippet illustrates the use of container queries with Mantine's SimpleGrid, allowing grid columns and spacing to adapt based on the container's width rather than the viewport. The example wraps the grid in a resizable div to demonstrate dynamic adjustments, with configuration objects specifying breakpoints and spacing values for different container widths. Dependencies include SimpleGrid from Mantine core.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.10.0.md#_snippet_2

LANGUAGE: TypeScript
CODE:

import { SimpleGrid } from '@mantine/core';

function Demo() { return ( // Wrapper div is added for demonstration purposes only, // it is not required in real projects <div style={{ resize: 'horizontal', overflow: 'hidden', maxWidth: '100%' }}> <SimpleGrid type="container" cols={{ base: 1, '300px': 2, '500px': 5 }} spacing={{ base: 10, '300px': 'xl' }} > <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </SimpleGrid> </div> ); }


----------------------------------------

TITLE: Demonstrating Correct and Incorrect Mantine Styles Import Order in TypeScript
DESCRIPTION: Provides examples of correct and incorrect styles import order for Mantine packages in a TypeScript project. Ensures that @mantine/core styles load before other Mantine packages to maintain style integrity. Import order is vital to avoid style conflicts; no parameters or dynamic logic are present—these are static import sequences.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/mantine-styles.mdx#_snippet_2

LANGUAGE: TypeScript
CODE:

// ✅ Correct order import '@mantine/core/styles.css'; import '@mantine/dates/styles.css'; // ❌ Incorrect order import '@mantine/dates/styles.css'; import '@mantine/core/styles.css';


----------------------------------------

TITLE: Using useInputState with Various Input Components in React
DESCRIPTION: Demonstrates how to use the useInputState hook with different input types including native HTML inputs, Mantine TextInput, and NumberInput components. The example compares implementation with useInputState against traditional useState approach.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-input-state.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { NumberInput, TextInput } from '@mantine/core'; import { useInputState } from '@mantine/hooks';

function WithUseInputState() { const [stringValue, setStringValue] = useInputState(''); const [numberValue, setNumberValue] = useInputState< string | number

(0);

return ( <> <input type="text" value={stringValue} onChange={setStringValue} /> <TextInput value={stringValue} onChange={setStringValue} /> <NumberInput value={numberValue} onChange={setNumberValue} /> </> ); }

function WithUseState() { const [stringValue, setStringValue] = useState(''); const [numberValue, setNumberValue] = useState<string | number>(0);

return ( <> <input type="text" value={stringValue} onChange={(event) => setStringValue(event.currentTarget.value) } /> <TextInput value={stringValue} onChange={(event) => setStringValue(event.currentTarget.value) } /> <NumberInput value={numberValue} onChange={setNumberValue} /> </> ); }


----------------------------------------

TITLE: Basic Usage of useLocalStorage Hook in React
DESCRIPTION: Demonstrates the basic usage of the useLocalStorage hook to store and retrieve a color scheme preference. The hook reads the initial value from localStorage or falls back to the provided default value, and automatically syncs state changes with localStorage.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-local-storage.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useLocalStorage } from '@mantine/hooks';

// The hook will read value from localStorage.getItem('color-scheme') // If localStorage is not available or value at a given key does not exist // 'dark' will be assigned to value variable const [value, setValue] = useLocalStorage({ key: 'color-scheme', defaultValue: 'dark', });

// Value is set both to state and localStorage at 'color-scheme' setValue('light');

// You can also use callback like in useState hook to set value setValue((current) => (current === 'dark' ? 'light' : 'dark'));


----------------------------------------

TITLE: Generating Custom Mantine Colors with colors-generator (TSX)
DESCRIPTION: This snippet shows how to use the `generateColors` function from `@mantine/colors-generator` to create a custom color palette based on a single hex value. The generated palette is then applied to a Mantine theme using `createTheme` and provided to the application via `MantineProvider`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-0-0.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { generateColors } from '@mantine/colors-generator'; import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({ colors: { 'pale-blue': generateColors('#375EAC'), }, });

function Demo() { return ( <MantineProvider theme={theme}> {/* Your app here */} </MantineProvider> ); }


----------------------------------------

TITLE: Popover Component with onDismiss Prop (TSX)
DESCRIPTION: This example illustrates the usage of the `onDismiss` prop in the Popover component to handle outside clicks and escape key presses for closing the popover. The snippet manages the popover's open state using the `useState` hook.  The `onDismiss` function sets the opened state to `false`, which allows for closing the popover when clicking outside the popover or pressing the escape key.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-17-0.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { Button, Popover } from '@mantine/core';

function Demo() { const [opened, setOpened] = useState(false); return ( <Popover opened={opened} onDismiss={() => setOpened(false)} > <Popover.Target> <Button onClick={() => setOpened((o) => !o)}> Toggle popover </Button> </Popover.Target>

  <Popover.Dropdown>Dropdown</Popover.Dropdown>
</Popover>

); }


----------------------------------------

TITLE: Initial Next.js Layout with Mantine ColorSchemeScript (Causes Warning)
DESCRIPTION: This code shows a basic Next.js `app/layout.tsx` file using Mantine's `ColorSchemeScript` in the `<head>`. This setup is presented as the cause of the hydration warning because the script modifies the `<html>` element before React hydrates.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/color-scheme-hydration-warning.mdx#_snippet_0

LANGUAGE: tsx
CODE:

// app/layout.tsx import { ColorSchemeScript, MantineProvider } from '@mantine/core';

export default function RootLayout({ children }: { children: any }) { return ( <html lang="en"> <head> <ColorSchemeScript /> <link rel="shortcut icon" href="/favicon.svg" /> <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, user-scalable=no" /> </head> <body> <MantineProvider>{children}</MantineProvider> </body> </html> ); }


----------------------------------------

TITLE: Validating Non-Empty Values with Mantine Form Validator in TypeScript
DESCRIPTION: This snippet demonstrates the isNotEmpty validation function from the @mantine/form package. It validates that form values are not empty according to Mantine's definition (empty string, empty array, false, null, or undefined). Validation errors contain custom error messages. The form is created using useForm hook with uncontrolled mode and initial values of different types to illustrate validation rules applied to multiple fields.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validators.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { isNotEmpty, useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { name: '', acceptTermsOfUse: false, country: null, previousJobs: [], },

validate: { // Empty strings are considered to be invalid name: isNotEmpty('Name cannot be empty'),

// False value is considered to be invalid
acceptTermsOfUse: isNotEmpty('You must accept terms of use'),

// null is considered to be invalid
country: isNotEmpty('Pick your country'),

// Empty arrays are considered to be invalid
previousJobs: isNotEmpty('Enter at least one job'),

}, });


----------------------------------------

TITLE: Managing Form Submission State with use-form Hook
DESCRIPTION: This snippet demonstrates tracking and manually controlling the submission state of a form using the 'useForm' hook's 'submitting' field and 'setSubmitting' method. It handles asynchronous submission and updates UI based on submission status.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-15-0.mdx#_snippet_6

LANGUAGE: TypeScript
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled' }); form.submitting; // -> false

form.setSubmitting(true); form.submitting; // -> true

form.setSubmitting(false); form.submitting; // -> false


----------------------------------------

TITLE: Initializing Mantine Form with TanStack Query Data (TSX)
DESCRIPTION: Demonstrates how to use the `form.initialize` handler to populate form values with data fetched asynchronously, specifically using TanStack Query. The `useEffect` hook ensures the form is initialized once the data is available.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-4-0.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { useEffect } from 'react'; import { useQuery } from '@tanstack/react-query'; import { useForm } from '@mantine/form';

function Demo() { const query = useQuery({ queryKey: ['current-user'], queryFn: () => fetch('/api/users/me').then((res) => res.json()), });

const form = useForm({ initialValues: { name: '', email: '', }, });

useEffect(() => { if (query.data) { // Even if query.data changes, form will be initialized only once form.initialize(query.data); } }, [query.data]); }


----------------------------------------

TITLE: Initializing Mantine Form with TanStack Query Data (TypeScript)
DESCRIPTION: This example demonstrates how to use `form.initialize` to populate form fields with data fetched asynchronously, specifically using TanStack Query. The `useEffect` hook ensures that the form is initialized only once when `query.data` becomes available, preventing re-initialization on subsequent data changes.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/get-input-props.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { useEffect } from 'react'; import { useQuery } from '@tanstack/react-query'; import { useForm } from '@mantine/form';

function Demo() { const query = useQuery({ queryKey: ['current-user'], queryFn: () => fetch('/api/users/me').then((res) => res.json()), });

const form = useForm({ mode: 'uncontrolled', initialValues: { name: '', email: '', }, });

useEffect(() => { if (query.data) { // Even if query.data changes, form will be initialized only once form.initialize(query.data); } }, [query.data]); }


----------------------------------------

TITLE: ActionIcon Example with Incorrect Elements
DESCRIPTION: This code demonstrates how to structure `ActionIcon.Group` component and indicates a common mistake, by wrapping `ActionIcon` components with additional `div` elements.  It serves to highlight correct and incorrect usage within the `ActionIcon.Group`, showing how such mistakes can affect the component's rendering and behavior.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/action-icon.mdx#_snippet_2

LANGUAGE: TypeScript
CODE:

import { ActionIcon } from '@mantine/core';

// Will not work correctly function Demo() { return ( <ActionIcon.Group> <div> <ActionIcon>This will not work</ActionIcon> </div> <ActionIcon>ActionIcons will have incorrect borders</ActionIcon> </ActionIcon.Group> ); }


----------------------------------------

TITLE: Invalid Mantine Group Usage with Non-Element Children
DESCRIPTION: This snippet demonstrates incorrect usage of the Mantine Group component by including strings, fragments, and numbers directly as children. This can lead to unexpected styling issues, especially when the 'grow' prop is used. Group requires valid React elements as its children for correct behavior.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/group.mdx#_snippet_0

LANGUAGE: tsx
CODE:

// Invalid Group usage, do not do this import { Group } from '@mantine/core';

function InvalidDemo() { return ( <Group grow> First string <> <div>element inside fragment</div> <div>another inside fragment</div> </> {20} </Group> ); }


----------------------------------------

TITLE: Tracking Touched and Dirty Fields - Mantine (TypeScript/TSX)
DESCRIPTION: This code segment covers methods for determining and controlling 'touched' and 'dirty' field flags within a useForm instance, which is useful for advanced UI feedback and validation triggers. Functions include status checks, completes sets, and resets for both touched and dirty states. These utilities depend solely on initialized useForm and use object maps or paths as input. Outputs are updated internal flags reflecting user interactions and unsaved changes.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_7

LANGUAGE: TSX
CODE:

// Returns true if user interacted with any field inside form in any way form.isTouched();

// Returns true if user interacted with field at specified path form.isTouched('path');

// Set all touched values form.setTouched({ 'user.firstName': true, 'user.lastName': false });

// Clears touched status of all fields form.resetTouched();

// Returns true if form values are not deep equal to initialValues form.isDirty();

// Returns true if field value is not deep equal to initialValues form.isDirty('path');

// Sets dirty status of all fields form.setDirty({ 'user.firstName': true, 'user.lastName': false });

// Clears dirty status of all fields, saves form.values snapshot // After form.resetDirty is called, form.isDirty will compare // form.getValues() to snapshot instead of initialValues form.resetDirty();


----------------------------------------

TITLE: Using Next.js Link with Mantine Button
DESCRIPTION: Demonstrates making a Mantine Button act as a Next.js Link component for client-side routing by setting the component prop.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/next.mdx#_snippet_8

LANGUAGE: TypeScript
CODE:

import Link from 'next/link'; import { Button } from '@mantine/core';

function Demo() { return ( <Button component={Link} href="/hello"> Next link button </Button> ); }


----------------------------------------

TITLE: Adding ColorSchemeScript in _document.tsx
DESCRIPTION: Defines a custom Document component that includes Mantine's ColorSchemeScript to support theme color schemes across server and client.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/next.mdx#_snippet_6

LANGUAGE: TypeScript
CODE:

import { Head, Html, Main, NextScript } from 'next/document'; import { ColorSchemeScript, mantineHtmlProps } from '@mantine/core';

export default function Document() { return ( <Html lang="en" {...mantineHtmlProps}> <Head> <ColorSchemeScript defaultColorScheme="auto" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); }


----------------------------------------

TITLE: Adding Clear Button to Inputs with Input.ClearButton in TypeScript React
DESCRIPTION: Illustrates how to enhance a Mantine Input component with the new Input.ClearButton to provide a clear (reset) button inside the input field. The clear button size automatically inherits from the input size. The example maintains local state for the input value and conditionally renders the clear button only when the value is non-empty. Requires React and @mantine/core package. Provides cleaner UX for clearing inputs easily.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.16.0.md#_snippet_2

LANGUAGE: tsx
CODE:

import { Input } from '@mantine/core'; import { useState } from 'react';

function Demo() { const [value, setValue] = useState('clearable');

return ( <Input placeholder="Clearable input" value={value} onChange={(event) => setValue(event.currentTarget.value)} rightSection={value !== '' ? <Input.ClearButton onClick={() => setValue('')} /> : undefined} rightSectionPointerEvents="auto" size="sm" /> ); }


----------------------------------------

TITLE: Adding OKLCH colors to custom Mantine theme in TypeScript
DESCRIPTION: Demonstrates how to extend Mantine's default theme colors by adding an 'oklch-blue' palette using OKLCH color values within a TypeScript React app. It shows the theme creation with createTheme, usage of MantineProvider to apply the theme globally, and rendering buttons styled with the custom OKLCH-based colors. Requires Mantine core components and React with TypeScript. The color array supports 10 shades defined by OKLCH CSS color strings.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_4

LANGUAGE: tsx
CODE:

import { Button, createTheme, Group, MantineProvider } from '@mantine/core';

const theme = createTheme({ colors: { 'oklch-blue': [ 'oklch(96.27% 0.0217 238.66)', 'oklch(92.66% 0.0429 240.01)', 'oklch(86.02% 0.0827 241.66)', 'oklch(78.2% 0.13 243.83)', 'oklch(71.8% 0.1686 246.06)', 'oklch(66.89% 0.1986 248.32)', 'oklch(62.59% 0.2247 250.29)', 'oklch(58.56% 0.2209 251.26)', 'oklch(54.26% 0.2067 251.67)', 'oklch(49.72% 0.1888 251.59)', ], }, });

function Demo() { return ( <MantineProvider theme={theme}> <Group> <Button color="oklch-blue">Filled</Button> <Button color="oklch-blue" variant="outline"> Outline </Button> <Button color="oklch-blue" variant="light"> Light </Button> </Group> </MantineProvider> ); }


----------------------------------------

TITLE: Creating Custom Mantine Theme - TypeScript
DESCRIPTION: This snippet defines a custom theme for the Mantine UI library. It uses the `createTheme` function to create a theme object. The `colors` property is used to define a custom color scheme named 'sepia' with a set of color shades. The theme object is then used with the `MantineProvider` to apply the theme to the application. Required dependencies include `@mantine/core`. The output is the rendered app with the sepia theme applied.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/light-dark-is-not-enough.mdx#_snippet_0

LANGUAGE: TypeScript
CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({ colors: { sepia: [ '#F4ECD8', '#EAD8B7', '#DFC29A', '#D4AC7E', '#C99862', '#BD8447', '#B2702D', '#A55C15', '#924908', '#7A3704', ], }, });

function Demo() { return ( <MantineProvider theme={theme}> <App /> </MantineProvider> ); }


----------------------------------------

TITLE: Implementing Collapsible Navbar with Desktop/Mobile States in React
DESCRIPTION: Example of implementing an AppShell with a navbar that has separate collapsed states for mobile and desktop viewports using useDisclosure hook for state management.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_10

LANGUAGE: tsx
CODE:

import { AppShell, Button } from '@mantine/core'; import { useDisclosure } from '@mantine/hooks';

export function CollapseDesktop() { const [mobileOpened, { toggle: toggleMobile }] = useDisclosure(); const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true);

return ( <AppShell padding="md" header={{ height: 60 }} navbar={{ width: 300, breakpoint: 'sm', collapsed: { mobile: !mobileOpened, desktop: !desktopOpened }, }} > <AppShell.Header>Header</AppShell.Header> <AppShell.Navbar>Navbar</AppShell.Navbar> <AppShell.Main> <Button onClick={toggleDesktop} visibleFrom="sm"> Toggle navbar </Button> <Button onClick={toggleMobile} hiddenFrom="sm"> Toggle navbar </Button> </AppShell.Main> </AppShell> ); }


----------------------------------------

TITLE: Using Container Queries with Mantine Grid (tsx)
DESCRIPTION: Demonstrates how to use container queries with the Mantine Grid component by setting the `type` prop to "container" and defining breakpoints based on container width. Includes a wrapper div for demonstration resizing.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.13.0.md#_snippet_0

LANGUAGE: tsx
CODE:

import { Grid } from '@mantine/core';

function Demo() { return ( // Wrapper div is added for demonstration purposes only, // it is not required in real projects <div style={{ resize: 'horizontal', overflow: 'hidden', maxWidth: '100%' }}> <Grid type="container" breakpoints={{ xs: '100px', sm: '200px', md: '300px', lg: '400px', xl: '500px' }} > <Grid.Col span={{ base: 12, md: 6, lg: 3 }}>1</Grid.Col> <Grid.Col span={{ base: 12, md: 6, lg: 3 }}>2</Grid.Col> <Grid.Col span={{ base: 12, md: 6, lg: 3 }}>3</Grid.Col> <Grid.Col span={{ base: 12, md: 6, lg: 3 }}>4</Grid.Col> </Grid> </div> ); }


----------------------------------------

TITLE: Controlling Form Submission Event Default with onSubmitPreventDefault - Mantine useForm Hook
DESCRIPTION: Provides a setup for the useForm hook with the onSubmitPreventDefault configuration option to control whether event.preventDefault is called on form submit. Option values include 'always' (default), 'never', and 'validation-failed'. Useful for integrating useForm with native browser form handling or server actions. Requires @mantine/form.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.15.0.md#_snippet_8

LANGUAGE: TSX
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', onSubmitPreventDefault: 'never', });


----------------------------------------

TITLE: Configuring Valibot Resolver for List Fields Validation
DESCRIPTION: This example illustrates Valibot validation on list fields within a form.  It uses `array` to define a schema for a list of objects. The schema is applied to the form with `valibotResolver`. Dependencies are `@mantine/form`, `valibot`, and `mantine-form-valibot-resolver`.  Validation errors are found in `form.errors` after calling `form.validate()`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_16

LANGUAGE: tsx
CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver'; import { array, minLength, object, string } from 'valibot'; import { useForm } from '@mantine/form';

const listSchema = object({ list: array( object({ name: string([minLength(2, 'Name should have at least 2 letters')]), }) ), });

const form = useForm({ initialValues: { list: [{ name: '' }], }, validate: valibotResolver(listSchema), });

form.validate(); form.errors; // -> { // 'list.0.name': 'Name should have at least 2 letters', // }


----------------------------------------

TITLE: Example of incorrect usage of hooks in server component
DESCRIPTION: This snippet illustrates a TypeScript component that attempts to use a React hook (`useDisclosure`) without the 'use client' directive, resulting in an error because hooks are not allowed in server components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_0

LANGUAGE: TypeScript
CODE:

// ❌ This will throw an error import { useDisclosure } from '@mantine/hooks';

function Demo() { const { opened, toggle } = useDisclosure(); return ( <button onClick={toggle}>{opened ? 'Opened' : 'Closed'}</button> ); }


----------------------------------------

TITLE: Implementing custom components with Tooltip using ref forwarding
DESCRIPTION: Demonstrates two approaches for creating custom components that work with Tooltip: using forwardRef and using a custom refProp. Both methods allow the Tooltip to access the DOM node for positioning.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tooltip.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { forwardRef } from 'react'; import { Tooltip } from '@mantine/core';

// forwardRef function will allow to get root element ref const MyBadge = forwardRef<HTMLDivElement, { color: string }>( ({ color }, ref) => ( <div ref={ref} color={color}> Badge </div> ) );

// other props can also be used function MyOtherBadge({ color, innerRef, }: { color: string; innerRef?: React.ForwardedRef<HTMLDivElement>; }) { return ( <div ref={innerRef} color={color}> Badge </div> ); }

function Demo() { return ( <> <Tooltip label="Can be used as is"> <MyBadge color="red" /> </Tooltip>

  <Tooltip label="refProp is required" refProp="innerRef">
    <MyOtherBadge color="orange" />
  </Tooltip>
</>

); }


----------------------------------------

TITLE: Implementing a Controlled Mantine Switch in TSX
DESCRIPTION: Demonstrates how to manage the checked state of a Mantine `Switch` component using the `useState` hook in React. The `checked` prop is bound to the state variable, and the `onChange` handler updates the state based on the event's `currentTarget.checked` value. Requires `react` and `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/switch.mdx#_snippet_0

LANGUAGE: tsx
CODE:

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)} /> ); }


----------------------------------------

TITLE: Augmenting Custom Variant Types for Mantine Button in TypeScript
DESCRIPTION: Provides a guide for augmenting Mantine's ButtonProps to allow custom variant types using TypeScript declaration merging. Depends on @mantine/core and use of type augmentation via declaration merging. The key parameter is the variant property, which can be set to extended string values. No runtime input/output; affects type safety during development. Limitation: the module augmentation must match the library's module structure.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.15.0.md#_snippet_13

LANGUAGE: TypeScript
CODE:

import { ButtonVariant, MantineSize } from '@mantine/core';

type ExtendedButtonVariant = ButtonVariant | 'contrast' | 'radial-gradient';

declare module '@mantine/core' { export interface ButtonProps { variant?: ExtendedButtonVariant; } }


----------------------------------------

TITLE: Generating and Adding Custom Colors to Mantine Theme (TSX)
DESCRIPTION: This example demonstrates how to use the `@mantine/colors-generator` package's `generateColors` function to create a 10-shade color palette from a single hex value. The generated palette is then added to the Mantine theme's `colors` object under a custom name (`'pale-blue'`) within a `MantineProvider`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/colors.mdx#_snippet_7

LANGUAGE: tsx
CODE:

import { generateColors } from '@mantine/colors-generator'; import { MantineProvider } from '@mantine/core';

function Demo() { return ( <MantineProvider theme={{ colors: { 'pale-blue': generateColors('#375EAC'), }, }} > {/* Your app here */} </MantineProvider> ); }


----------------------------------------

TITLE: Using useShallowEffect with Various Dependency Types in React
DESCRIPTION: Shows how `useShallowEffect` handles different types of dependencies including primitives, arrays of primitives, objects of primitives, and arrays of objects. It illustrates which dependency changes will trigger the effect based on shallow equality rules.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-shallow-effect.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { useShallowEffect } from '@mantine/hooks';

// Primitive values are handled like in useEffect useShallowEffect(() => {}, [1, 2, 3]);

// Arrays with primitive values will not trigger callback useShallowEffect(() => {}, [[1], [2], [3]]);

// Objects with primitive values will not trigger callback useShallowEffect(() => {}, [{ a: 1 }, { b: 2 }]);

// Arrays with objects will trigger callback since values are not shallow equal useShallowEffect(() => {}, [[{ a: 1 }], [{ b: 2 }]]);


----------------------------------------

TITLE: Defining and Using Field Validation - Mantine (TypeScript/TSX)
DESCRIPTION: This snippet demonstrates how to define per-field validation logic within useForm, using both field-level and nested object validators as well as invoking different validation methods. Dependencies include @mantine/form; all validation callbacks receive current field values as input and return either an error message or null. Outputs are updated error objects within the form instance. The structure supports both flat and nested validation schemas.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_3

LANGUAGE: TSX
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { email: '', user: { firstName: '', lastName: '', }, }, validate: { email: (value) => (value.length < 2 ? 'Invalid email' : null), user: { firstName: (value) => value.length < 2 ? 'First name must have at least 2 letters' : null, }, }, });

// Validates all fields with specified validate function or schema, sets form.errors form.validate();

// Validates single field at specified path, sets form.errors form.validateField('user.firstName');

// Works the same way as form.validate but does not set form.errors form.isValid(); form.isValid('user.firstName');


----------------------------------------

TITLE: Disabling Inputs Using Mantine use-form enhanceGetInputProps Hook (JavaScript)
DESCRIPTION: Shows how to disable all inputs in a form that utilizes Mantine's use-form hook by leveraging the enhanceGetInputProps function. This approach allows dynamic control over input states based on form logic, simplifying the process without wrapping inputs in a Fieldset.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/disable-all-inputs-in-form.mdx#_snippet_1

LANGUAGE: JavaScript
CODE:

import { EnhanceDisableInputs } from '@/demos/EnhanceDisableInputs.demo'; import { Layout } from '@/layout';

// Usage of enhanceGetInputProps: // Pass or set options in use-form to generate enhanced input properties. // These can include a disabled state, which when applied to inputs, disables them.

// Example component: // <Demo data={EnhanceDisableInputs} />


----------------------------------------

TITLE: Testing Welcome Component with Custom Utilities (TSX)
DESCRIPTION: This example test imports the custom render function and other test utilities, then tests that the Welcome component links to the correct Next.js guide. It demonstrates the use of screen.getByText and assertion helpers from Testing Library. Dependencies: Welcome component, MantineProvider setup, custom test-utils. Inputs are UI components, outputs are test assertions. Consistent use of custom utilities ensures all Mantine context is initialized during tests.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/vitest.mdx#_snippet_5

LANGUAGE: TSX
CODE:

import { render, screen } from '../test-utils'; import { Welcome } from './Welcome';

describe('Welcome component', () => { it('has correct Next.js theming section link', () => { render(<Welcome />); expect(screen.getByText('this guide')).toHaveAttribute( 'href', 'https://mantine.dev/guides/next/' ); }); });


----------------------------------------

TITLE: Controlled AngleSlider with React's useState hook
DESCRIPTION: Shows how to implement a controlled AngleSlider component using React's useState hook, enabling manual control over the slider's value and handling changes via the onChange prop.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/angle-slider.mdx#_snippet_1

LANGUAGE: TypeScript
CODE:

import { useState } from 'react'; import { AngleSlider } from '@mantine/core';

function Demo() { const [value, setValue] = useState(180); return <AngleSlider value={value} onChange={setValue} />; }


----------------------------------------

TITLE: Defining Virtual Color in Mantine Theme (TSX)
DESCRIPTION: Demonstrates how to define a virtual color in a Mantine theme using the `virtualColor` function. This allows a single color name to have different values for light and dark color schemes, enhancing theme adaptability.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.7.0.md#_snippet_0

LANGUAGE: tsx
CODE:

import { createTheme, MantineProvider, virtualColor } from '@mantine/core';

const theme = createTheme({ colors: { primary: virtualColor({ name: 'primary', dark: 'pink', light: 'cyan', }), }, });

function App() { return <MantineProvider theme={theme}>{/* Your app here */}</MantineProvider>; }


----------------------------------------

TITLE: Combining Multiple Refs with useMergedRef in Mantine (TypeScript)
DESCRIPTION: This snippet shows how to use Mantine's useMergedRef hook to combine multiple refs and attach them to a single DOM node in a React function component. It demonstrates integration with useClickOutside and useFocusTrap hooks from @mantine/hooks. Dependencies include react and @mantine/hooks. Inputs are refs from useRef and Mantine hooks; output is a merged ref function to assign to a DOM element's ref prop.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-merged-ref.mdx#_snippet_0

LANGUAGE: TSX
CODE:

import { useRef } from 'react'; import { useClickOutside, useFocusTrap, useMergedRef, } from '@mantine/hooks';

function Demo() { const myRef = useRef(); const useClickOutsideRef = useClickOutside(() => {}); const focusTrapRef = useFocusTrap(); const mergedRef = useMergedRef( myRef, useClickOutsideRef, focusTrapRef );

return <div ref={mergedRef} />; }


----------------------------------------

TITLE: Extend Component with Styles, ClassNames, and Default Props (TSX)
DESCRIPTION: Demonstrates using the static `extend` function on a Mantine component (TextInput) within the theme definition. This allows for type-safe customization of `styles`, `classNames`, and `defaultProps`, providing autocomplete for theme properties and component props.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_4

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { TextInput, MantineProvider, createTheme } from '@mantine/core'; import classes from './Demo.module.css';

const theme = createTheme({ components: { TextInput: TextInput.extend({ styles: (theme, props) => ({ input: { fontSize: props.size === 'compact' ? theme.fontSizes.sm : undefined, } }), classNames: { root: classes.root, input: classes.input, label: classes.label, },

  defaultProps: {
    size: 'compact',
  },
}),

}, });

function Demo() { return ( <MantineProvider theme={theme}> <App /> </MantineProvider> ); }


----------------------------------------

TITLE: Referencing Theme Colors and Custom Colors in Style Props (TypeScript TSX)
DESCRIPTION: Demonstrates Mantine Box components using color-related style props ('c' for color, 'bd' for border, 'bg' for background) with both theme tokens and direct color values. The example includes scenarios where the applied color depends on the current color scheme (light/dark), as indicated by special tokens like 'dimmed' or 'bright', as well as hardcoded CSS colors. Requires @mantine/core and Mantine theme setup. Props accept theme color tokens, CSS color strings, or functional tokens that resolve based on the active color scheme.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/style-props.mdx#_snippet_2

LANGUAGE: TSX
CODE:

import { Box } from '@mantine/core';

function Demo() { return ( <> {/* color: theme.colors.blue[theme.primaryShade] */} <Box c="blue" />

  {/* background: theme.colors.orange[1] */}
  <Box bg="orange.1" />

  {/* border: 1px solid theme.colors.red[6] */}
  <Box bd="1px solid red.6" />

  {/* color: if colorScheme is dark `var(--mantine-color-dark-2)`,
  if color scheme is light `var(--mantine-color-gray-6)` */}
  <Box c="dimmed" />

  {/* color: if colorScheme is dark `var(--mantine-color-white)`,
  if color scheme is light `var(--mantine-color-black)` */}
  <Box c="bright" />

  {/* background: #EDFEFF */}
  <Box bg="#EDFEFF" />

  {/* background: rgba(0, 34, 45, 0.6) */}
  <Box bg="rgba(0, 34, 45, 0.6)" />
</>

); }


----------------------------------------

TITLE: Using MantineSize Type for Props (TypeScript)
DESCRIPTION: Demonstrates how to use the `MantineSize` union type to define props that accept predefined size values. The example shows an interface `DemoProps` using `MantineSize` for `size`, `radius`, and `shadow` props and a component using these typed props with the `Paper` component.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_7

LANGUAGE: tsx
CODE:

import { MantineSize, Paper } from '@mantine/core';

interface DemoProps { size: MantineSize; radius: MantineSize | (string & {}) | number; shadow: MantineSize | string; }

function Demo({ size, radius, shadow }: DemoProps) { return <Paper radius={radius} shadow={shadow} p={size} m={size} />; }


----------------------------------------

TITLE: Comparing form.values and form.getValues in Uncontrolled Mantine Form
DESCRIPTION: Highlights the difference between accessing `form.values` and calling `form.getValues()` when using `useForm` in `uncontrolled` mode, particularly after a value update. It shows that `form.values` becomes stale, while `form.getValues()` correctly reflects the immediate change made by `setFieldValue`, emphasizing its use for current values in uncontrolled scenarios.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-8-0.mdx#_snippet_4

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { name: 'John Doe' }, });

const handleNameChange = () => { form.setFieldValue('name', 'Test Name');

// ❌ Do not use form.values to get the current form values // form.values has stale name value until next rerender in controlled mode // and is always outdated in uncontrolled mode console.log(form.values); // { name: 'John Doe' }

// ✅ Use form.getValues to get the current form values // form.getValues always returns the latest form values console.log(form.getValues()); // { name: 'Test Name' } };


----------------------------------------

TITLE: Mantine Tabs with react-router
DESCRIPTION: Shows how to integrate Mantine Tabs with react-router.  The `useNavigate` and `useParams` hooks are used to synchronize the active tab with the URL.  Changing the tab updates the URL, and vice versa. Requires react-router-dom.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tabs.mdx#_snippet_4

LANGUAGE: typescript
CODE:

import { useNavigate, useParams } from 'react-router-dom'; import { Tabs } from '@mantine/core';

function Demo() { const navigate = useNavigate(); const { tabValue } = useParams();

return ( <Tabs value={tabValue} onChange={(value) => navigate(/tabs/${value})} > <Tabs.List> <Tabs.Tab value="first">First tab</Tabs.Tab> <Tabs.Tab value="second">Second tab</Tabs.Tab> </Tabs.List> </Tabs> ); }


----------------------------------------

TITLE: Configuring global autoContrast and luminanceThreshold in theme with @mantine/core in TypeScript
DESCRIPTION: Shows how to enable the global 'autoContrast' setting and adjust the 'luminanceThreshold' in Mantine's theme via createTheme. It programmatically generates buttons with variable color shades to demonstrate dynamic text color switching based on background luminance. Requires @mantine/core and React with TypeScript. Applies theme through MantineProvider and renders a stack of buttons to visualize contrast adjustments.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_6

LANGUAGE: tsx
CODE:

import { Button, createTheme, MantineProvider, Stack } from '@mantine/core';

const theme = createTheme({ autoContrast: true, luminanceThreshold: 0.3, });

function Wrapper(props: any) { const buttons = Array(10) .fill(0) .map((_, index) => ( <Button key={index} color={blue.${index}}> Button </Button> ));

return ( <MantineProvider theme={theme}> <Stack>{buttons}</Stack> </MantineProvider> ); }


----------------------------------------

TITLE: Creating Component Variants with `withProps` in Mantine (TSX)
DESCRIPTION: Demonstrates using the `withProps` static function on Mantine components like `Button` and `InputBase` to define new components (`LinkButton`, `PhoneInput`) with pre-configured default props. It also shows overriding these defaults and integrating external components like `IMaskInput`. Dependencies include `@mantine/core` and `react-imask`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.11.0.md#_snippet_0

LANGUAGE: tsx
CODE:

import { IMaskInput } from 'react-imask'; import { Button, InputBase } from '@mantine/core';

const LinkButton = Button.withProps({ component: 'a', target: '_blank', rel: 'noreferrer', variant: 'subtle', });

const PhoneInput = InputBase.withProps({ mask: '+7 (000) 000-0000', component: IMaskInput, label: 'Your phone number', placeholder: 'Your phone number', });

function Demo() { return ( <> {/* You can pass additional props to components created with withProps */} <LinkButton href="https://mantine.dev">Mantine website</LinkButton>

  {/* Component props override default props defined in `withProps` */}
  <PhoneInput placeholder="Personal phone" />
</>

); }


----------------------------------------

TITLE: Implementing Custom Options Filtering in Mantine Select with TypeScript
DESCRIPTION: This TypeScript/React snippet shows how to define a custom filter function for the Mantine Select component using the filter prop. The filter logic splits both the search query and each option into words, returning only options that contain all search words as substrings in their labels. Requires @mantine/core for Select, ComboboxItem, and OptionsFilter types and components. The component expects a data array of option strings and supports case-insensitive, word-based partial matching.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/select-fuzzy.mdx#_snippet_0

LANGUAGE: TypeScript
CODE:

import { Select, ComboboxItem, OptionsFilter } from '@mantine/core';

const optionsFilter: OptionsFilter = ({ options, search }) => { const splittedSearch = search.toLowerCase().trim().split(' '); return (options as ComboboxItem[]).filter((option) => { const words = option.label.toLowerCase().trim().split(' '); return splittedSearch.every((searchWord) => words.some((word) => word.includes(searchWord))); }); };

function Demo() { return ( <Select label="Your country" placeholder="Pick value" data={["Great Britain", "Russian Federation", "United States"]} filter={optionsFilter} searchable /> ); }


----------------------------------------

TITLE: Importing Individual Mantine Component Styles with CSS Layer in TypeScript
DESCRIPTION: Shows how to import component-level Mantine styles wrapped with the @layer mantine directive for granular style management in a TypeScript React application. Applies when developers need only certain components layered for specificity. Each import corresponds to a component, and '... other styles' can be appended for additional components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/mantine-styles.mdx#_snippet_6

LANGUAGE: TypeScript
CODE:

import '@mantine/core/styles/UnstyledButton.layer.css'; import '@mantine/core/styles/Button.layer.css';

// ... other styles


----------------------------------------

TITLE: Rendering modal content inside Portal with React and TypeScript
DESCRIPTION: Demonstrates rendering a modal-like component in a Portal using React and TypeScript. Utilizes useState to toggle visibility. The Portal component renders the modal content outside the parent 'main' element, preventing z-index and position style conflicts. Dependencies include React and @mantine/core's Portal component. The snippet shows expected inputs (state toggling) and outputs (a div rendered in Portal).
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/portal.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { Portal } from '@mantine/core';

function Demo() { const [opened, setOpened] = useState(false);

return ( <main style={{ position: 'relative', zIndex: 1 }}> {opened && ( <Portal> <div>Your modal content</div> </Portal> )}

  <button onClick={() => setOpened(true)} type="button">
    Open modal
  </button>
</main>

); }


----------------------------------------

TITLE: Custom Value Formatter for MonthPickerInput
DESCRIPTION: Shows how to implement a custom valueFormatter function for more advanced formatting control, especially useful for different component types.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/month-picker-input.mdx#_snippet_5

LANGUAGE: jsx
CODE:
<Demo data={MonthPickerInputDemos.valueFormatter} /> ```

TITLE: Referencing Mantine Theme Tokens in SCSS Modules DESCRIPTION: Shows how to use CSS variables like --mantine-color-red-5, --mantine-spacing-md, and --mantine-font-family-headings to access Mantine theme values within CSS modules. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/styles-overview.mdx#_snippet_7

LANGUAGE: scss CODE:

.root {
  // references theme.colors.red[5]
  background: var(--mantine-color-red-5);

  // references theme.spacing.md
  margin-top: var(--mantine-spacing-md);

  // references theme.headings.fontFamily
  font-family: var(--mantine-font-family-headings);
}

TITLE: Defining Custom Colors with colorsTuple in Mantine (TSX) DESCRIPTION: Illustrates how to use the colorsTuple helper function to define custom color palettes in the Mantine theme. It shows examples for creating a tuple from a single color value (repeated 10 times) and from a dynamic array of 10 color strings, ensuring the required 10 shades are present. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/colors.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { colorsTuple, createTheme } from '@mantine/core';

const theme = createTheme({
  colors: {
    custom: colorsTuple('#FFC0CB'),
    dynamic: colorsTuple(
      Array.from({ length: 10 }, (_, index) => '#FFC0CB')
    ),
  },
});

TITLE: Generating and Adding Custom Colors to Mantine Theme (TSX) DESCRIPTION: This snippet illustrates how to use the generateColors function from @mantine/colors-generator to create a color palette from a single hex value (#375EAC). The generated palette is then added to the Mantine theme under a custom key ('pale-blue') within the MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_15

LANGUAGE: tsx CODE:

import { generateColors } from '@mantine/colors-generator';
import { MantineProvider } from '@mantine/core';

function Demo() {
  return (
    <MantineProvider
      theme={{
        colors: {
          'pale-blue': generateColors('#375EAC'),
        },
      }}
    >
      <App />
    </MantineProvider>
  );
}

TITLE: Customizing primaryShade for Light/Dark Schemes in Mantine (TSX) DESCRIPTION: Demonstrates how to configure the theme.primaryShade property to use different default color shades based on the current color scheme (light or dark). This allows components using the primary color to adapt their shade automatically based on the user's preference. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/colors.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { MantineProvider } from '@mantine/core';

function Demo() {
  return (
    <MantineProvider theme={{ primaryShade: { light: 6, dark: 8 } }}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Defining a Mantine Theme in TypeScript DESCRIPTION: Defines a custom Mantine theme using the createTheme function from @mantine/core. This theme object specifies properties like fontFamily and primaryColor and needs to be passed to the MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/vanilla-extract.mdx#_snippet_0

LANGUAGE: tsx CODE:

// theme.ts
import { createTheme } from '@mantine/core';

// Do not forget to pass theme to MantineProvider
export const theme = createTheme({
  fontFamily: 'serif',
  primaryColor: 'cyan',
});

TITLE: Validating List Fields with Zod and useForm DESCRIPTION: This snippet focuses on validating list fields using Zod with Mantine Form. It defines a schema for a list of objects and uses zodResolver to connect with useForm. The example shows how the validation errors for the list items are structured. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { zodResolver } from 'mantine-form-zod-resolver';
import { z } from 'zod';
import { useForm } from '@mantine/form';

const listSchema = z.object({
  list: z.array(
    z.object({
      name: z
        .string()
        .min(2, { message: 'Name should have at least 2 letters' }),
    })
  ),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    list: [{ name: '' }],
  },
  validate: zodResolver(listSchema),
});

form.validate();
form.errors;
// -> {
//  'list.0.name': 'Name should have at least 2 letters',
// }

TITLE: Mantine Tabs with Next.js router DESCRIPTION: Demonstrates how to integrate Mantine Tabs with the Next.js router. The useRouter hook is used to synchronize the active tab with the URL query parameter activeTab. Changing the tab updates the URL, and vice versa. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tabs.mdx#_snippet_5

LANGUAGE: typescript CODE:

// For file /tabs/[activeTab].tsx
import { useRouter } from 'next/router';
import { Tabs } from '@mantine/core';

function Demo() {
  const router = useRouter();

  return (
    <Tabs
      value={router.query.activeTab as string}
      onChange={(value) => router.push(`/tabs/${value}`)}
    >
      <Tabs.List>
        <Tabs.Tab value="first">First tab</Tabs.Tab>
        <Tabs.Tab value="second">Second tab</Tabs.Tab>
      </Tabs.List>
    </Tabs>
  );
}

TITLE: Importing Mantine Core Styles with CSS Layers (TSX) DESCRIPTION: Demonstrates importing Mantine core styles using the .layer.css file. This method places Mantine styles within a CSS layer, allowing regular styles imported later to easily override them, regardless of import order. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.1.0.md#_snippet_0

LANGUAGE: tsx CODE:

// If your styles are not wrapped in @layer directive,
// they will be applied after Mantine styles.
// Import order does not affect styles in this case
import classes from './Demo.module.css';
import '@mantine/core/styles.layer.css';

TITLE: Basic Usage of useClickOutside Hook in React DESCRIPTION: Demonstrates the basic implementation of the useClickOutside hook. The hook returns a ref that should be attached to the target element, and the provided handler function is called when a click occurs outside this element. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-click-outside.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useClickOutside } from '@mantine/hooks';

function Example() {
  const handleClickOutside = () =>
    console.log('Clicked outside of div');
  const ref = useClickOutside(handleClickOutside);
  return <div ref={ref} />;
}

TITLE: Using Image w, h, and fallbackSrc Props (TSX) DESCRIPTION: This code snippet demonstrates the changes to the Mantine Image component, specifically using the w and h style props for dimensions and the fallbackSrc prop to display a placeholder image when the primary source is null. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_21

LANGUAGE: tsx CODE:

import { Image } from '@mantine/core';

function Demo() {
  return (
    <Image
      radius="md"
      src={null}
      h={200}
      fallbackSrc="https://placehold.co/600x400?text=Placeholder"
    />
  );
}

TITLE: Implementing Controlled Mantine usePagination DESCRIPTION: Shows how to use the usePagination hook with external state management, specifically using React's useState. It demonstrates passing the current page state (page) and an update function (onChange) to the hook to enable controlled behavior. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-pagination.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { usePagination } from '@mantine/hooks';

const [page, onChange] = useState(1);
const pagination = usePagination({ total: 10, page, onChange });

// Will call onChange with 5
pagination.setPage(5);
pagination.range; // -> [1, 'dots', 4, 5, 6, 'dots', 10];

// ... All other examples work the same

TITLE: Importing Required Global Mantine Styles (tsx) DESCRIPTION: Shows the essential global CSS files that all Mantine components depend on. These include a minimal reset (baseline.css), default CSS variables (default-css-variables.css), and global utility classes (global.css). These must be imported before other component styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-files-list.mdx#_snippet_2

LANGUAGE: tsx CODE:

import '@mantine/core/styles/baseline.css';
import '@mantine/core/styles/default-css-variables.css';
import '@mantine/core/styles/global.css';

TITLE: Defining and Using Context Modals with ModalsProvider in TypeScript DESCRIPTION: Defines a context modal component (TestModal) accepting typed inner props and context for modal management. This component includes closing logic via context.closeModal and renders custom content with a close button. The modals are registered in ModalsProvider's modals prop by key. Enables modular and reusable modals referenced by keys for dynamic opening. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/modals.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { Button, Text } from '@mantine/core';
import { ContextModalProps, ModalsProvider } from '@mantine/modals';

const TestModal = ({
  context,
  id,
  innerProps,
}: ContextModalProps<{ modalBody: string }>) => (
  <>
    <Text size="sm">{innerProps.modalBody}</Text>
    <Button fullWidth mt="md" onClick={() => context.closeModal(id)}>
      Close modal
    </Button>
  </>
);

function Demo() {
  return (
    <ModalsProvider
      modals={{ demonstration: TestModal /* ...other modals */ }}
    >
      {/* Your app here */}
    </ModalsProvider>
  );
}

TITLE: Managing Multiple Modals with Modal.Stack and useModalsStack Hook in TypeScript React DESCRIPTION: Demonstrates usage of Mantine's Modal.Stack component combined with the useModalsStack hook to manage multiple modal dialogs simultaneously. The hook accepts an array of unique modal IDs and controls modal opening, closing, and stacking with proper z-index management, focus trap, and escape key handling. The example shows three modals with cascading open/close behavior and buttons triggering state changes. Dependencies include '@mantine/core' and internal hook useModalsStack. Inputs are modal IDs and user interactions; outputs are modal visibility states and focus management. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.14.0.md#_snippet_3

LANGUAGE: tsx CODE:

import { Button, Group, Modal, useModalsStack } from '@mantine/core';

function Demo() {
  const stack = useModalsStack(['delete-page', 'confirm-action', 'really-confirm-action']);

  return (
    <>
      <Modal.Stack>
        <Modal {...stack.register('delete-page')} title="Delete this page?">
          Are you sure you want to delete this page? This action cannot be undone.
          <Group mt="lg" justify="flex-end">
            <Button onClick={stack.closeAll} variant="default">
              Cancel
            </Button>
            <Button onClick={() => stack.open('confirm-action')} color="red">
              Delete
            </Button>
          </Group>
        </Modal>

        <Modal {...stack.register('confirm-action')} title="Confirm action">
          Are you sure you want to perform this action? This action cannot be undone. If you are
          sure, press confirm button below.
          <Group mt="lg" justify="flex-end">
            <Button onClick={stack.closeAll} variant="default">
              Cancel
            </Button>
            <Button onClick={() => stack.open('really-confirm-action')} color="red">
              Confirm
            </Button>
          </Group>
        </Modal>

        <Modal {...stack.register('really-confirm-action')} title="Really confirm action">
          Jokes aside. You have confirmed this action. This is your last chance to cancel it. After
          you press confirm button below, action will be performed and cannot be undone. For real
          this time. Are you sure you want to proceed?
          <Group mt="lg" justify="flex-end">
            <Button onClick={stack.closeAll} variant="default">
              Cancel
            </Button>
            <Button onClick={stack.closeAll} color="red">
              Confirm
            </Button>
          </Group>
        </Modal>
      </Modal.Stack>

      <Button onClick={() => stack.open('delete-page')}>Open modal</Button>
    </>
  );
}

TITLE: Using the use-field Hook for Form Validation in React DESCRIPTION: Shows how to use the new use-field hook from @mantine/form to manage a single input field state with validation, which serves as a simpler alternative to the use-form hook. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.9.0.md#_snippet_1

LANGUAGE: tsx CODE:

import { TextInput } from '@mantine/core';
import { isEmail, useField } from '@mantine/form';

function Demo() {
  const field = useField({
    initialValue: '',
    validateOnChange: true,
    validate: isEmail('Invalid email'),
  });

  return <TextInput {...field.getInputProps()} label="Email" placeholder="Enter your email" />;
}

TITLE: Configuring Mantine Theme Scale for Rem Units - TypeScript DESCRIPTION: This TypeScript example illustrates how to configure the scale property within the Mantine theme using createTheme and MantineProvider. Setting scale to 1 / (htmlFontSize / 16) ensures that Mantine components maintain their intended visual size even when the html element's font-size is altered from its default 16px. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/rem.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  scale: 1.6,
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Using Mantine Button with Custom Color and Variant in TSX DESCRIPTION: This TypeScript React snippet illustrates how to use the Mantine Button component with a specified color and variant prop. It shows a Button configured with color='pink' and variant='filled', demonstrating how these props influence the component's appearance based on theme-defined variant colors. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_20

LANGUAGE: tsx CODE:

import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button color="pink" variant="filled">
      Filled pink button
    </Button>
  );
}

TITLE: Using Mantine Form Actions Externally (TSX) DESCRIPTION: This example illustrates how to use the created form actions (demoFormActions) from a component that does not have direct access to the form state. It demonstrates calling setValues to update form fields based on fetched data and reset to clear the form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-2-0.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { useEffect } from 'react';
import { Button } from '@mantine/core';
import { demoFormActions } from './demoFormActions';

function ExternalComponent() {
  useEffect(() => {
    fetch('/api/user')
      .then((res) => res.json())
      .then((res) =>
        demoFormActions.setValues({
          name: res.name,
          age: res.age,
        })
      );
  }, []);

  return (
    <Button onClick={() => demoFormActions.reset()}>
      Reset demo form
    </Button>
  );
}

TITLE: Best Practices for Accessing Form Values with getValues vs values DESCRIPTION: Comparison showing why form.getValues() should be used instead of form.values to get current form values, especially after field value changes. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/uncontrolled.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { name: 'John Doe' },
});

const handleNameChange = () => {
  form.setFieldValue('name', 'Test Name');

  // ❌ Do not use form.values to get the current form values
  // form.values has stale name value until next rerender in controlled mode
  // and is always outdated in uncontrolled mode
  console.log(form.values); // { name: 'John Doe' }

  // ✅ Use form.getValues to get the current form values
  // form.getValues always returns the latest form values
  console.log(form.getValues()); // { name: 'Test Name' }
};

TITLE: Avatar.Group Usage with incorrect wrapping in Mantine DESCRIPTION: This code shows an example of how the Avatar.Group component should not be used. It's demonstrating incorrect usage where extra HTML elements (div tags) are used to wrap the Avatar components. This will lead to the avatars not rendering correctly within the group. It's important to avoid wrapping Avatar components with additional elements inside Avatar.Group. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/avatar.mdx#_snippet_1

LANGUAGE: tsx CODE:

// Will not work correctly
function Demo() {
  return (
    <Avatar.Group spacing="sm">
      <div>
        <Avatar src="image.png" radius="xl" />
      </div>
      <Avatar src="image.png" radius="xl" />
      <Avatar src="image.png" radius="xl" />
      <Avatar radius="xl">+5</Avatar>
    </Avatar.Group>
  );
}

TITLE: Using form.getInputNode to Focus Input DOM Elements in React Mantine Form DESCRIPTION: This code demonstrates the form.getInputNode(path) method, allowing programmatic access to input DOM nodes based on form field paths. It is utilized within an uncontrolled form with email and name fields, enabling focus management when form submission results in errors by focusing the first erroneous input. Dependencies include Mantine core components and the useForm hook. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.10.0.md#_snippet_1

LANGUAGE: TypeScript CODE:

import { Button, Group, TextInput } from '@mantine/core';
import { isEmail, isNotEmpty, useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    mode: 'uncontrolled',
    initialValues: {
      name: '',
      email: '',
    },

    validate: {
      name: isNotEmpty('Name is required'),
      email: isEmail('Invalid email'),
    },
  });

  return (
    <form
      onSubmit={form.onSubmit(
        (values) => console.log(values),
        (errors) => {
          const firstErrorPath = Object.keys(errors)[0];
          form.getInputNode(firstErrorPath)?.focus();
        }
      )}
    >
      <TextInput
        withAsterisk
        label="Your name"
        placeholder="Your name"
        key={form.key('name')}
        {...form.getInputProps('name')}
      />

      <TextInput
        withAsterisk
        label="Your email"
        placeholder="your@email.com"
        key={form.key('email')}
        {...form.getInputProps('email')}
      />

      <Group justify="flex-end" mt="md">
        <Button type="submit">Submit</Button>
      </Group>
    </form>
  );
}


TITLE: Migrating theme referencing to CSS variables DESCRIPTION: Shows how to migrate from referencing theme object in 6.x to using CSS variables in 7.x for styling. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/6x-to-7x.mdx#_snippet_9

LANGUAGE: tsx CODE:

// 6.x
import { Box } from '@mantine/core';

function Demo() {
  return (
    <Box
      sx={(theme) => ({
        backgroundColor: theme.colors.red[6],
        color: theme.white,
        padding: `calc(${theme.spacing.xl} * 2)`,
      })}
    />
  );
}

LANGUAGE: scss CODE:

/* 7.0 */
.box {
  background-color: var(--mantine-color-red-6);
  color: var(--mantine-color-white);
  padding: calc(var(--mantine-spacing-xl) * 2);
}

TITLE: Demonstrating Limitations and Correct Patterns for Using Timeline.Item in Mantine with TypeScript DESCRIPTION: This code snippet explains that wrapping Timeline.Item components directly in other components is unsupported, as the Timeline component relies on the immediate order of Timeline.Item elements. It shows an invalid example where Timeline.Item is wrapped directly in a component (which prevents rendering), contrasted with a valid pattern where child components are nested inside Timeline.Item to maintain correct rendering order. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/timeline.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { Timeline } from '@mantine/core';

// This will not work, step children will not render
function WillNotWork() {
  return <Timeline.Item title="Nope">It will not work</Timeline.Item>;
}

// Create a separate component for children
function WillWork() {
  return <div>This will work as expected!</div>;
}

function Demo() {
  return (
    <Timeline active={1}>
      <Timeline.Item title="Regular item">First item</Timeline.Item>
      <WillNotWork />
      <Timeline.Item title="Works as expected">
        <WillWork />
      </Timeline.Item>
      <Timeline.Item title="Regular item">Third item</Timeline.Item>
    </Timeline>
  );
}

TITLE: Providing component and renderRoot Props to a Non-polymorphic Component (Mantine Group, TypeScript) DESCRIPTION: Illustrates that non-polymorphic Mantine components now accept 'component' and 'renderRoot' props. The Group component is rendered as a 'nav' element, with children links inside. Requires Mantine v7.3.0 or newer. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.3.0.md#_snippet_7

LANGUAGE: tsx CODE:

import { Group } from '@mantine/core';

// Group is not polymorphic component,
// but it still supports component and renderRoot props
function Demo() {
  return (
    <Group component="nav">
      <a>Item 1</a>
      <a>Item 2</a>
      <a>Item 3</a>
    </Group>
  );
}

TITLE: UseInterval Hook API Usage in Mantine (TSX) DESCRIPTION: Illustrates how to capture the return value of the useInterval hook, which provides control over the interval. The returned object includes start, stop, toggle functions and an active status boolean. Requires @mantine/hooks. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-interval.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useInterval } from '@mantine/hooks';

const { start, stop, toggle, active } = useInterval(fn, interval);

TITLE: Validating Nested Fields with Zod and useForm DESCRIPTION: This snippet illustrates how to validate nested fields using Zod with Mantine Form. It defines a schema for a nested object and uses zodResolver to integrate it with the form. The useForm hook is used, and the example demonstrates accessing validation errors for nested fields. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { zodResolver } from 'mantine-form-zod-resolver';
import { z } from 'zod';
import { useForm } from '@mantine/form';

const nestedSchema = z.object({
  nested: z.object({
    field: z
      .string()
      .min(2, { message: 'Field should have at least 2 letters' }),
  }),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    nested: {
      field: '',
    },
  },
  validate: zodResolver(nestedSchema),
});

form.validate();
form.errors;
// -> {
//  'nested.field': 'Field should have at least 2 letters',
// }

TITLE: Validating List Fields with Yup and useForm DESCRIPTION: This snippet demonstrates validating list fields using Yup with Mantine Form. It defines a Yup schema for an array of objects. The example showcases how the validation results are structured for the array items. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { yupResolver } from 'mantine-form-yup-resolver';
import * as yup from 'yup';
import { useForm } from '@mantine/form';

const listSchema = yup.object().shape({
  list: yup.array().of(
    yup.object().shape({
      name: yup
        .string()
        .min(2, 'Name should have at least 2 letters'),
    })
  ),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    list: [{ name: '' }],
  },
  validate: yupResolver(listSchema),
});

form.validate();
form.errors;
// -> {
//  'list.0.name': 'Name should have at least 2 letters',
// }

TITLE: Implementing accessibility features in AngleSlider DESCRIPTION: Provides an example of making the AngleSlider accessible by supporting keyboard interactions for adjusting the angle, and setting aria-label for screen readers to improve accessibility. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/angle-slider.mdx#_snippet_5

LANGUAGE: JSX CODE:

import { AngleSlider } from '@mantine/core';

function Demo() {
  return <AngleSlider aria-label="Gradient angle" />;
}

TITLE: Validating Nested Fields with Superstruct and useForm DESCRIPTION: This snippet shows the validation of nested fields using Superstruct with Mantine Form. It defines a Superstruct schema for nested fields and integrates it with the useForm hook via superstructResolver, demonstrating how to access validation errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_10

LANGUAGE: tsx CODE:

import { superstructResolver } from 'mantine-form-superstruct-resolver';
import * as s from 'superstruct';
import { useForm } from '@mantine/form';

const nestedSchema = s.object({
  nested: s.object({
    field: s.size(s.string(), 2, 30),
  }),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    nested: {
      field: '',
    },
  },
  validate: superstructResolver(nestedSchema),
});

form.validate();
form.errors;
// -> {
//  'nested.field': 'nested field: Expected a string with a length between `2` and `30` but received one with a length of `0`',
// }

TITLE: Initializing Mantine Combobox with useCombobox Hook in TypeScript DESCRIPTION: Demonstrates the creation of a Combobox component with state management provided by the useCombobox hook from Mantine. The hook returns a store that holds current state and handlers for the Combobox, and the store is passed to the Combobox component via the store prop. This setup enables flexible control over selection and dropdown behavior. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/combobox.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { Combobox, useCombobox } from '@mantine/core';

function Demo() {
  const combobox = useCombobox();
  return (
    <Combobox store={combobox}>{/* Your implementation */}</Combobox>
  );
}

TITLE: Installing @mantinex/mantine-meta npm Package Using Bash DESCRIPTION: This snippet shows the commands required to install the @mantinex/mantine-meta package via yarn and npm package managers. It is intended for users to add the package as a dependency in their JavaScript or TypeScript projects that use the Mantine framework. The commands should be run in a terminal or command prompt within the project directory. No additional dependencies are required beyond yarn or npm itself. SOURCE: https://github.com/mantinedev/mantine/blob/master/packages/@mantinex/mantine-meta/README.md#_snippet_0

LANGUAGE: bash CODE:

# With yarn
yarn add @mantinex/mantine-meta

# With npm
npm install @mantinex/mantine-meta

TITLE: Installing Mantine Dropzone with Yarn - Bash DESCRIPTION: This snippet demonstrates the installation of the @mantine/dropzone, @mantine/core, and @mantine/hooks packages using the yarn package manager. It's a prerequisite step to use the Mantine Dropzone component within a project. No specific parameters are needed; it simply installs the listed dependencies. The output is the successful installation of the specified packages. SOURCE: https://github.com/mantinedev/mantine/blob/master/packages/@mantine/dropzone/README.md#_snippet_0

LANGUAGE: bash CODE:

yarn add @mantine/dropzone @mantine/core @mantine/hooks

TITLE: Install Mantine Form package - Bash DESCRIPTION: Provides commands to install the Mantine Form library as a project dependency using either yarn or npm package managers. This is a required prerequisite to use the library in a project. SOURCE: https://github.com/mantinedev/mantine/blob/master/packages/@mantine/form/README.md#_snippet_0

LANGUAGE: bash CODE:

yarn add @mantine/form

LANGUAGE: bash CODE:

npm install @mantine/form

TITLE: Polymorphic Badge Component Usage with Next.js Integration (JSX/React) DESCRIPTION: This snippet demonstrates the polymorphic rendering of the Badge component by switching the base element from a 'div' to an 'a' tag using the <Polymorphic> utility. This feature, enabled via the 'withNext' prop, increases flexibility when integrating the Badge component in navigation or link-rich contexts such as Next.js routing. The snippet assumes Polymorphic utility is available and properly configured within the Mantine project. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/badge.mdx#_snippet_2

LANGUAGE: JSX CODE:

<Polymorphic
  defaultElement="div"
  changeToElement="a"
  component="Badge"
  withNext
/>

TITLE: Avoiding Duplicate Mantine Style Imports in TypeScript DESCRIPTION: Warns against importing both regular and layered versions of Mantine styles in the same TypeScript project. Importing both versions can cause style conflicts and should be avoided. Only one of the styles.css or styles.layer.css should be imported for each package/component. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/mantine-styles.mdx#_snippet_5

LANGUAGE: TypeScript CODE:

// ❌ Do not import both styles.css and styles.layer.css
import '@mantine/core/styles.css';
import '@mantine/core/styles.layer.css';

TITLE: Specifying Item Type with useListState DESCRIPTION: When the useListState hook is initialized with an empty array, the item type needs to be specified explicitly to avoid the type being inferred as any. This shows correct usages of the hook with and without specifying a type. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-list-state.mdx#_snippet_15

LANGUAGE: tsx CODE:

import { useListState } from '@mantine/hooks';

useListState(['hello']); // ok, item type is string
useListState([]); // not ok, item type is any
useListState<string>([]); // ok, item type is string

TITLE: Implementing RTL Styles in Vanilla Extract (TypeScript) DESCRIPTION: Demonstrates how to apply styles specifically for right-to-left (RTL) layouts using the vars.rtlSelector. This selector is used within the selectors property of the style function to override or add styles when the application's direction is RTL. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/vanilla-extract.mdx#_snippet_7

LANGUAGE: tsx CODE:

// Demo.css.ts
import { style } from '@vanilla-extract/css';
import { vars } from './theme';

export const demo = style({
  paddingRight: vars.spacing.md,

  selectors: {
    [vars.rtlSelector]: {
      paddingLeft: vars.spacing.md,
      paddingRight: 0,
    },
  },
});

TITLE: Integrating Google Fonts Links and Mantine Theme in React Router TSX DESCRIPTION: Imports Mantine core styles and sets up the basic React Router root.tsx structure. Demonstrates how to include the Google Fonts <link> tags directly within the <head> element of the Layout component. Configures the Mantine theme to use the Google Font. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/react-router-load-fonts.mdx#_snippet_3

LANGUAGE: tsx CODE:

import '@mantine/core/styles.css';
import './Roboto/styles.css';

import {
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from 'react-router';
import {
  ColorSchemeScript,
  createTheme,
  DEFAULT_THEME,
  MantineProvider,
} from '@mantine/core';

const theme = createTheme({
  fontFamily: 'Roboto, sans-serif',
  fontFamilyMonospace: 'Monaco, Courier, monospace',
  headings: {
    // Use default theme if you want to provide default Mantine fonts as a fallback
    fontFamily: `Roboto, ${DEFAULT_THEME.fontFamily}`,
  },
});

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1"
        />
        <Meta />
        <Links />
        <ColorSchemeScript />
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link
          rel="preconnect"
          href="https://fonts.gstatic.com"
          crossOrigin=""
        />
        <link
          href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
          rel="stylesheet"
        />
      </head>
      <body>
        <MantineProvider theme={theme}>{children}</MantineProvider>
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export default function App() {
  return <Outlet />;
}

TITLE: Creating Scrollable Sections in AppShell Navbar with AppShell.Section DESCRIPTION: Example showing how to create a layout with fixed header/footer sections and a scrollable middle section in an AppShell.Navbar using the AppShell.Section component with ScrollArea. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_17

LANGUAGE: tsx CODE:

import { AppShell, ScrollArea } from '@mantine/core';

function Demo() {
  return (
    <AppShell navbar={{ width: 300, breakpoint: 0 }}>
      <AppShell.Navbar>
        <AppShell.Section>Navbar header</AppShell.Section>
        <AppShell.Section grow component={ScrollArea}>
          Navbar main section, it will
        </AppShell.Section>
        <AppShell.Section>
          Navbar footer – always at the bottom
        </AppShell.Section>
      </AppShell.Navbar>
      <AppShell.Main>Main</AppShell.Main>
    </AppShell>
  );
}

TITLE: Integrating Local Fonts and Mantine Theme in React Router TSX DESCRIPTION: Imports the local custom font CSS file and Mantine core styles. Configures the Mantine theme object to use the custom font for fontFamily and headings.fontFamily. Sets up the basic React Router root.tsx structure including MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/react-router-load-fonts.mdx#_snippet_1

LANGUAGE: tsx CODE:

import '@mantine/core/styles.css';
import './Roboto/styles.css';

import {
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from 'react-router';
import {
  ColorSchemeScript,
  createTheme,
  DEFAULT_THEME,
  MantineProvider,
  mantineHtmlProps,
} from '@mantine/core';

const theme = createTheme({
  fontFamily: 'Roboto, sans-serif',
  fontFamilyMonospace: 'Monaco, Courier, monospace',
  headings: {
    // Use default theme if you want to provide default Mantine fonts as a fallback
    fontFamily: `Roboto, ${DEFAULT_THEME.fontFamily}`,
  },
});

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" {...mantineHtmlProps}>
      <head>
        <meta charSet="utf-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1"
        />
        <Meta />
        <Links />
        <ColorSchemeScript />
      </head>
      <body>
        <MantineProvider theme={theme}>{children}</MantineProvider>
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export default function App() {
  return <Outlet />;
}

TITLE: Using MantineThemeOverride Type (TypeScript) DESCRIPTION: Demonstrates the usage of the MantineThemeOverride type for functions that handle theme overrides. The example shows how to define a function that accepts an array of theme overrides and merges them with a base theme using mergeThemeOverrides. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_5

LANGUAGE: tsx CODE:

import {
  createTheme,
  MantineThemeOverride,
  mergeThemeOverrides,
} from '@mantine/core';

const baseTheme = createTheme({
  fontFamily: 'Helvetica, sans-serif',
});

function mergeThemes(themes: MantineThemeOverride[]) {
  return mergeThemeOverrides(baseTheme, ...themes);
}

const overrideTheme = createTheme({
  primaryColor: 'blue',
});

const overrideTheme2 = createTheme({
  cursorType: 'pointer',
});

const mergedTheme = mergeThemes([overrideTheme, overrideTheme2]);

TITLE: Implementing useReducedMotion Hook Definition DESCRIPTION: This TypeScript snippet defines the useReducedMotion hook. The hook accepts an optional initialValue boolean, which allows for specifying an initial value, especially relevant during server-side rendering where window.matchMedia might not be available. The options parameter is an object that can contain getInitialValueInEffect which is a boolean. The hook returns a boolean indicating whether the user prefers reduced motion. This hook leverages the window.matchMedia() API under the hood to detect the user's motion preferences based on the prefers-reduced-motion media query. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-reduced-motion.mdx#_snippet_0

LANGUAGE: typescript CODE:

function useReducedMotion(
  initialValue?: boolean,
  options?: {
    getInitialValueInEffect: boolean;
  }
): boolean;

TITLE: Incorrect Usage of Mantine Button.Group in TSX DESCRIPTION: Demonstrates an incorrect way to structure components within Mantine's Button.Group. Wrapping individual Button components within extra elements like <div> disrupts the CSS selectors Button.Group uses to apply styles (like borders) correctly to its direct children. Buttons should be direct children of Button.Group for proper rendering. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/button.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button.Group>
      <div>
        <Button>This will not work</Button>
      </div>
      <Button>Buttons will have incorrect borders</Button>
    </Button.Group>
  );
}

TITLE: Using TagsInput with React useState for controlled value DESCRIPTION: This snippet demonstrates managing the TagsInput component's value using React's useState hook, making it a controlled component. It initializes an empty array of strings as the state, passing it to TagsInput via the data, value, and onChange props. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tags-input.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

import { useState } from 'react';
import { TagsInput } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState<string[]>([]);
  return <TagsInput data={[]} value={value} onChange={setValue} />;
}

TITLE: Using renderRoot with react-router-dom NavLink (TSX) DESCRIPTION: Shows how to use the renderRoot prop to wrap a Mantine component with a react-router-dom NavLink. It uses a callback function to pass props and handle className logic, which is necessary because NavLink expects className to be a function, unlike Mantine components. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-1-0.mdx#_snippet_3

LANGUAGE: tsx CODE:

import cx from 'clsx';
import { NavLink } from 'react-router-dom';
import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button
      renderRoot={({ className, ...others }) => (
        <NavLink
          className={({ isActive }) =>
            cx(className, { 'active-class': isActive })
          }
          {...others}
        />
      )}
    >
      React router NavLink
    </Button>
  );
}

TITLE: Enabling System Color Scheme - TSX DESCRIPTION: Demonstrates how to configure MantineProvider and ColorSchemeScript with defaultColorScheme="auto" to enable support for the user's preferred system color scheme (prefers-color-scheme). SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-0-0.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { ColorSchemeScript, MantineProvider } from '@mantine/core';

function Demo() {
  return (
    <>
      <ColorSchemeScript defaultColorScheme="auto" />
      <MantineProvider defaultColorScheme="auto">
        {/* Your app here */}
      </MantineProvider>
    </>
  );
}

TITLE: Adding Grouped Object Options to Mantine NativeSelect (TSX) DESCRIPTION: This snippet illustrates how to define grouped options using the data prop with a more complex object structure. Each item in the main array represents a group with a group label and an items array containing option objects (with label, value, and optional disabled). SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/native-select.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { NativeSelect } from '@mantine/core';

function Demo() {
  return (
    <NativeSelect
      data={[
        {
          group: 'Frontend libraries',
          items: [
            { label: 'React', value: 'react' },
            { label: 'Angular', value: 'angular' },
            { label: 'Vue', value: 'vue', disabled: true },
          ],
        },
        {
          group: 'Backend libraries',
          items: [
            { label: 'Express', value: 'express' },
            { label: 'Koa', value: 'koa' },
            { label: 'Django', value: 'django' },
          ],
        },
      ]}
    />
  );
}

TITLE: Using Mantine VisuallyHidden with ActionIcon (TSX) DESCRIPTION: Demonstrates integrating the Mantine VisuallyHidden component with an ActionIcon in a React functional component. VisuallyHidden hides the provided text 'Like post' from the visual display, ensuring it's still available to screen readers for improved accessibility when the icon is focused. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/visually-hidden.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { IconHeart } from '@tabler/icons-react';
import { ActionIcon, VisuallyHidden } from '@mantine/core';

function Demo() {
  return (
    <ActionIcon>
      <IconHeart />
      <VisuallyHidden>Like post</VisuallyHidden>
    </ActionIcon>
  );
}

TITLE: Importing All Mantine Global Styles (TSX) DESCRIPTION: Imports the main global styles file from @mantine/core, which includes all necessary base styles for Mantine components to function correctly. This is the recommended approach for most applications. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/global-styles.mdx#_snippet_0

LANGUAGE: tsx CODE:

import '@mantine/core/styles.css';

TITLE: Using Form Context from a Separate File - Main Form Component DESCRIPTION: Example of implementing the main form component that initializes the form with useUserForm and provides the form context to child components with UserFormProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/create-form-context.mdx#_snippet_3

LANGUAGE: tsx CODE:

// UserForm.tsx
import { NumberInput } from '@mantine/core';
import { UserFormProvider, useUserForm } from './form-context';
import { NameInput } from './NameInput';

function UserForm() {
  const form = useUserForm({
    mode: 'uncontrolled',
    initialValues: {
      age: 0,
      name: '',
    },
  });

  return (
    <UserFormProvider form={form}>
      <form onSubmit={form.onSubmit(() => {})}>
        <NumberInput
          label="Age"
          key={form.key('age')}
          {...form.getInputProps('age')}
        />
        <NameInput />
      </form>
    </UserFormProvider>
  );
}

TITLE: Client-Side Usage of useMediaQuery Hook in Mantine DESCRIPTION: Demonstrates how to import and utilize the useMediaQuery hook to subscribe to media query changes, triggering re-renders on viewport resize. Highlights reliance on window.matchMedia() API and behavior when API is unavailable. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-media-query.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

import { HooksDemos } from '@docs/demos';
import { Layout } from '@/layout';
import { MDX_DATA } from '@/mdx';

export default Layout(MDX_DATA.useMediaQuery);

TITLE: Using useWindowEvent to Manage Keyboard Events with Mantine (TypeScript) DESCRIPTION: This code snippet demonstrates two approaches to handling window-level keyboard events in React using TypeScript: the conventional useEffect method and the more concise useWindowEvent hook from the @mantine/hooks package. Dependencies include React and @mantine/hooks. The examples show how to add and remove a keydown event listener, log the KeyboardEvent object, and leverage hook-based API for cleaner component lifecycles. Key parameters are the event type and the keyboard event handler function. The inputs are keyboard events; there is no meaningful output beyond side effects (logging). SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-window-event.mdx#_snippet_0

LANGUAGE: TSX CODE:

import { useEffect } from 'react';
import { useWindowEvent } from '@mantine/hooks';

const handler = (event: KeyboardEvent) => console.log(event);

// regular way
useEffect(() => {
  window.addEventListener('keydown', handler);
  return () => window.removeEventListener('keydown', handler);
}, []);

// with use-window-event hook
useWindowEvent('keydown', handler);

TITLE: Performing Shallow Object Equality Check with Mantine Hooks (TSX) DESCRIPTION: Illustrates the shallowEqual function from @mantine/hooks. This function performs a shallow comparison between two objects or arrays to determine if they are equal at the first level of properties/elements. Requires importing shallowEqual from the hooks package. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/functions-reference.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { shallowEqual } from '@mantine/hooks';

shallowEqual({ a: 1 }, { a: 1 }); // true
shallowEqual({ a: 1 }, { a: 2 }); // false

TITLE: Specifying Value Type with useUncontrolled (TSX) DESCRIPTION: Shows how to explicitly define the data type (e.g., number) for the state managed by useUncontrolled using TypeScript generics. This example sets up the hook with numeric value, defaultValue, and finalValue. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-uncontrolled.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useUncontrolled } from '@mantine/hooks';

function Demo() {
  const [_value, handleChange] = useUncontrolled<number>({
    value: 10,
    defaultValue: 5,
    finalValue: 20,
    onChange: (val) => console.log(val > 10),
  });
}

TITLE: Uncontrolled Form Implementation with useForm Hook DESCRIPTION: This TypeScript code provides an example of using the useForm hook in uncontrolled mode. It demonstrates how to define initial values, validate form fields, and handle form submission. Dependencies include @mantine/core for UI components and @mantine/form for form management. The component uses form.getInputProps and form.onSubmit. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.8.0.md#_snippet_2

LANGUAGE: TypeScript CODE:

import { useState } from 'react';
import { Button, Code, Text, TextInput } from '@mantine/core';
import { hasLength, isEmail, useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    mode: 'uncontrolled',
    initialValues: { name: '', email: '' },
    validate: {
      name: hasLength({ min: 3 }, 'Must be at least 3 characters'),
      email: isEmail('Invalid email'),
    },
  });

  const [submittedValues, setSubmittedValues] = useState<typeof form.values | null>(null);

  return (
    <form onSubmit={form.onSubmit(setSubmittedValues)}>
      <TextInput {...form.getInputProps('name')} label="Name" placeholder="Name" />
      <TextInput {...form.getInputProps('email')} mt="md" label="Email" placeholder="Email" />
      <Button type="submit" mt="md">
        Submit
      </Button>

      <Text mt="md">Form values:</Text>
      <Code block>{JSON.stringify(form.values, null, 2)}</Code>

      <Text mt="md">Submitted values:</Text>
      <Code block>{submittedValues ? JSON.stringify(submittedValues, null, 2) : '–'}</Code>
    </form>
  );
}

TITLE: Augmenting Mantine Theme Types for Custom Sizes (TypeScript) DESCRIPTION: This snippet illustrates how to augment Mantine's theme types to include custom spacing and radius values. By extending MantineThemeSizesOverride within a module declaration, developers can add new size definitions like 'xxl', 'xxxs', or 'xxs' to the spacing and radius properties, enhancing type safety and auto-completion for theme customization. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/8-0-0.mdx#_snippet_4

LANGUAGE: tsx CODE:

import {
  DefaultMantineSize,
  MantineThemeSizesOverride,
} from '@mantine/core';

type ExtendedCustomSpacing =
  | 'xxl'
  | 'xxxs'
  | DefaultMantineSize;

type ExtendedCustomRadius =
  | 'xxs'
  | DefaultMantineSize;

declare module '@mantine/core' {
  export interface MantineThemeSizesOverride {
    spacing: Record<ExtendedCustomSpacing, string>;
    radius: Record<ExtendedCustomRadius, string>;
  }
}

TITLE: Getting Color Scheme in Client-Side React with useMantineColorScheme DESCRIPTION: Demonstrates how to use the useMantineColorScheme hook from @mantine/core to access the current color scheme value in a React component. This method is suitable for client-side rendering frameworks like Vite but can cause hydration mismatches in server-side rendering frameworks like Next.js. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/light-dark-elements.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useMantineColorScheme } from '@mantine/core';

function MyComponent() {
  const { colorScheme } = useMantineColorScheme();

  // ✅ Works in Vite and other client-side bundlers/frameworks
  // ❌ Hydration mismatch in Next.js, React Router, and other server-side rendering frameworks
  return <div>Color scheme is {colorScheme}</div>;
}

TITLE: Implementing Custom Mantine Variant Color Resolver (TSX) DESCRIPTION: This snippet defines a variantColorResolver function that customizes how component colors and variants are resolved. It shows examples of overriding the 'filled' variant for a specific color ('lime'), completely redefining the 'light' variant, and adding a new 'danger' variant with custom background, hover, color, and border styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_10

LANGUAGE: tsx CODE:

import {
  Button,
  darken,
  defaultVariantColorsResolver,
  Group,
  MantineProvider,
  parseThemeColor,
  rem,
  rgba,
  VariantColorsResolver,
} from '@mantine/core';

const variantColorResolver: VariantColorsResolver = (input) => {
  const defaultResolvedColors = defaultVariantColorsResolver(input);
  const parsedColor = parseThemeColor({
    color: input.color || input.theme.primaryColor,
    theme: input.theme,
  });

  // Override some properties for variant
  if (parsedColor.isThemeColor && parsedColor.color === 'lime' && input.variant === 'filled') {
    return { ...defaultResolvedColors, color: 'var(--mantine-color-black)' };
  }

  // Completely override variant
  if (input.variant === 'light') {
    return {
      background: rgba(parsedColor.value, 0.1),
      hover: rgba(parsedColor.value, 0.15),
      border: `${rem(1)} solid ${parsedColor.value}`,
      color: darken(parsedColor.value, 0.1),
    };
  }

  // Add new variants support
  if (input.variant === 'danger') {
    return {
      background: 'var(--mantine-color-red-9)',
      hover: 'var(--mantine-color-red-8)',
      color: 'var(--mantine-color-white)',
      border: 'none',
    };
  }

  return defaultResolvedColors;
};

function Demo() {
  return (
    <MantineProvider theme={{ variantColorResolver }}>
      <Group>
        <Button color="lime.4" variant="filled">
          Lime filled button
        </Button>

        <Button color="orange" variant="light">
          Orange light button
        </Button>

        <Button variant="danger">Danger button</Button>
      </Group>
    </MantineProvider>
  );
}

TITLE: Customizing DatePicker Control Aria Labels (tsx) DESCRIPTION: Shows how to use the getDayProps, getYearControlProps, and getMonthControlProps functions to dynamically set the aria-label attribute for individual day, year, and month controls based on their respective dates. This provides more specific context for screen reader users. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/date-picker.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { DatePicker } from '@mantine/dates';

function Demo() {
  return (
    <DatePicker
      getDayProps={(date) => ({
        'aria-label': `Select date ${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`,
      })}
      getYearControlProps={(date) => ({
        'aria-label': `Select year ${date.getFullYear()}`,
      })}
      getMonthControlProps={(date) => ({
        'aria-label': `Select month ${date.getFullYear()}/${date.getMonth()}`,
      })}
    />
  );
}

TITLE: Checking Length Constraints with Mantine Form hasLength Validator in TypeScript DESCRIPTION: This snippet uses hasLength validator to validate whether the length of form values (strings, arrays, or any object with a length property) falls within specified minimum and maximum ranges. It trims strings before validation. The form validates four fields with different length constraints including exact, minimum, maximum, and between min-max lengths, all managed by the useForm hook. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validators.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { hasLength, useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    exact: '',
    maxLength: '',
    minLength: '',
    minMaxLength: '',
  },

  validate: {
    exact: hasLength(5, 'Values must have exactly 5 characters'),
    maxLength: hasLength(
      { max: 20 },
      'Value must have 20 or less characters'
    ),
    minLength: hasLength(
      { min: 10 },
      'Value must have 10  or more characters'
    ),
    minMaxLength: hasLength(
      { min: 10, max: 20 },
      'Value must have 10-20 characters'
    ),
  },
});

TITLE: Customizing Select Options with renderOption in Mantine (TSX) DESCRIPTION: Demonstrates using the renderOption prop on Mantine's Select component to customize the rendering of dropdown options. A custom function renderSelectOption receives option data and checked status, returning a React node with an icon, label, and a checkmark if selected. This feature is also available for MultiSelect, TagsInput, and Autocomplete components. Dependencies include @mantine/core for components and types, and @tabler/icons-react for icons. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.6.0.md#_snippet_0

LANGUAGE: tsx CODE:

import {
  IconAlignCenter,
  IconAlignJustified,
  IconAlignLeft,
  IconAlignRight,
  IconCheck,
} from '@tabler/icons-react';
import { Group, Select, SelectProps } from '@mantine/core';

const iconProps = {
  stroke: 1.5,
  color: 'currentColor',
  opacity: 0.6,
  size: 18,
};

const icons: Record<string, React.ReactNode> = {
  left: <IconAlignLeft {...iconProps} />,
  center: <IconAlignCenter {...iconProps} />,
  right: <IconAlignRight {...iconProps} />,
  justify: <IconAlignJustified {...iconProps} />,
};

const renderSelectOption: SelectProps['renderOption'] = ({ option, checked }) => (
  <Group flex="1" gap="xs">
    {icons[option.value]}
    {option.label}
    {checked && <IconCheck style={{ marginInlineStart: 'auto' }} {...iconProps} />}
  </Group>
);

function Demo() {
  return (
    <Select
      label="Select with renderOption"
      placeholder="Select text align"
      data={[
        { value: 'left', label: 'Left' },
        { value: 'center', label: 'Center' },
        { value: 'right', label: 'Right' },
        { value: 'justify', label: 'Justify' },
      ]}
      renderOption={renderSelectOption}
    />
  );
}

TITLE: Get computed color scheme with useComputedColorScheme in React component (TSX) DESCRIPTION: Demonstrates how to get the computed color scheme value (resolved from 'auto' to either 'dark' or 'light') within a React component using the useComputedColorScheme hook from @mantine/core. This hook utilizes localStorage and is not suitable for server-side rendering (SSR). SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/how-to-get-color-scheme-value-in-js.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useComputedColorScheme } from '@mantine/core';

function Demo() {
  // colorScheme is `'dark' | 'light'`
  const colorScheme = useComputedColorScheme();
}

TITLE: Rendering custom suggestion options with renderOption DESCRIPTION: This snippet demonstrates how to provide a custom rendering function for suggestion options via 'renderOption', which receives each option object and returns a React node for display, allowing highly customized dropdown options. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tags-input.mdx#_snippet_9

LANGUAGE: TypeScript CODE:

<Demo data={TagsInputDemos.renderOption} />

TITLE: Incorrect CSS Import Order for Mantine Overrides (TSX) DESCRIPTION: Demonstrates an incorrect import order where importing user styles before Mantine's core styles can lead to Mantine styles overriding user-defined styles due to cascade order. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/styles-order.mdx#_snippet_0

LANGUAGE: tsx CODE:

// ❌ Wrong order – Mantine styles override your styles
import './styles.css';
import '@mantine/core/styles.css';

TITLE: Showing Mantine Card.Section Usage Restrictions and Fragment Limitations in TypeScript DESCRIPTION: This snippet demonstrates the limitations of wrapping Card.Section components within other elements such as divs or React fragments inside a Card component. It imports Card, sets padding="xl", and attempts to wrap Card.Section inside a div and a fragment, both of which are unsupported and won't behave as expected. The code highlights the requirement that Card.Section must be a direct child of Card for correct negative margin calculation and layout styling. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/card.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { Card } from '@mantine/core';

function Demo() {
  return (
    <Card padding="xl">
      <div>
        <Card.Section>Won't work</Card.Section>
      </div>

      <>
        <Card.Section>Won't work either</Card.Section>
      </>

      <Card.Section>Works fine</Card.Section>
    </Card>
  );
}

TITLE: Implementing Command/Ctrl+K Focus Shortcut with useWindowEvent (TypeScript) DESCRIPTION: This snippet defines a Demo component using React and @mantine/hooks to focus an input when ⌘+K (Mac) or Ctrl+K (Windows/Linux) is pressed. It uses useRef for referencing the input and useWindowEvent to add a keydown listener. Dependencies are React and @mantine/hooks. The main parameters are the keydown event and the inputRef. When the shortcut is detected, the input is focused and default browser action is prevented. Limitations: The component assumes inputRef is attached to a single input and only processes keydown events for the K key combined with modifier keys. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-window-event.mdx#_snippet_1

LANGUAGE: TSX CODE:

import { useRef } from 'react';
import { useWindowEvent } from '@mantine/hooks';

function Demo() {
  const inputRef = useRef<HTMLInputElement>(null);

  useWindowEvent('keydown', (event) => {
    if (event.code === 'KeyK' && (event.ctrlKey || event.metaKey)) {
      event.preventDefault();
      inputRef.current?.focus();
    }
  });

  return <input ref={inputRef} />;
}

TITLE: Using Mantine ElementProps Utility Type (TypeScript) DESCRIPTION: Demonstrates various uses of the ElementProps utility type. It shows how to get native element props, omit specific props, and remove all Mantine component props from native element props, providing flexibility in type definitions. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { ButtonProps, ElementProps } from '@mantine/core';

// Equivalent of `React.ComponentPropsWithoutRef<'button'>`
type ButtonElementProps = ElementProps<'button'>;

// Equivalent of `Omit<React.ComponentPropsWithoutRef<'button'>, 'color' | 'onClick'>`
type OmitColor = ElementProps<'button', 'color' | 'onClick'>;

// Removes all Mantine component props from React component props
// to avoid props types conflicts
// Equivalent of `Omit<React.ComponentPropsWithoutRef<'button'>, keyof ButtonProps>`
type OmitButtonProps = ElementProps<'button', keyof ButtonProps>;

TITLE: Implementing Async Validation with use-field Hook in React DESCRIPTION: Demonstrates how to use the use-field hook with asynchronous validation, including showing a loading indicator during validation and triggering validation on button click. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.9.0.md#_snippet_2

LANGUAGE: tsx CODE:

import { Button, Loader, TextInput } from '@mantine/core';
import { useField } from '@mantine/form';

function validateAsync(value: string): Promise<string | null> {
  return new Promise((resolve) => {
    window.setTimeout(() => {
      resolve(value === 'mantine' ? null : 'Value must be "mantine"');
    }, 800);
  });
}

function Demo() {
  const field = useField({
    initialValue: '',
    validate: validateAsync,
  });

  return (
    <>
      <TextInput
        {...field.getInputProps()}
        label="Enter 'mantine'"
        placeholder="Enter 'mantine'"
        rightSection={field.isValidating ? <Loader size={18} /> : null}
        mb="md"
      />
      <Button onClick={field.validate}>Validate async</Button>
    </>
  );
}

TITLE: Defining Custom Button Variants Type in Mantine DESCRIPTION: This snippet shows how to extend the ButtonProps interface in Mantine to include custom variant types like 'contrast' and 'radial-gradient'. This allows TypeScript to recognize these new variants when using the Button component, improving type safety. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/variants-sizes.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { ButtonVariant, MantineSize } from '@mantine/core';

type ExtendedButtonVariant = ButtonVariant | 'contrast' | 'radial-gradient';

declare module '@mantine/core' {
  export interface ButtonProps {
    variant?: ExtendedButtonVariant;
  }
}

TITLE: Setting Default Props for Mantine Compound Components (tsx) DESCRIPTION: This example shows how to set default props for Mantine's compound components (e.g., Menu.Item, Tabs.List) within the createTheme object. It targets the components by their combined name (e.g., MenuItem, TabsList) without the dot notation and applies the theme globally using MantineProvider, causing instances of these components to inherit the defined defaults. Requires react and @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/default-props.mdx#_snippet_1

LANGUAGE: tsx CODE:

import {
  createTheme,
  MantineProvider,
  Menu,
  Tabs,
} from '@mantine/core';

const theme = createTheme({
  components: {
    MenuItem: Menu.Item.extend({
      defaultProps: { color: 'red' },
    }),

    TabsList: Tabs.List.extend({
      defaultProps: {
        justify: 'center',
      },
    }),
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Controlled RangeSlider Component in Mantine (TSX) DESCRIPTION: Shows how to implement a controlled Mantine RangeSlider component using React's useState hook to manage the range value (an array of two numbers). SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/slider.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { RangeSlider } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState<[number, number]>([20, 80]);
  return <RangeSlider value={value} onChange={setValue} />;
}

TITLE: Initializing DirectionProvider and MantineProvider in React with TypeScript DESCRIPTION: Example React functional component demonstrating the setup of Mantine's DirectionProvider and MantineProvider components to enable right-to-left or left-to-right direction control across the application. The DirectionProvider wraps MantineProvider, providing direction context to all nested Mantine components. This is crucial when implementing RTL support or dynamic direction changes in Mantine-based React applications. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/rtl.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { DirectionProvider, MantineProvider } from '@mantine/core';

function Demo() {
  return (
    <DirectionProvider>
      <MantineProvider>{/* Your app here */}</MantineProvider>
    </DirectionProvider>
  );
}

TITLE: Extending Polymorphic Mantine Component Props (TypeScript) DESCRIPTION: Illustrates how to extend the props type of a polymorphic Mantine component (Button). It uses ElementProps to include native element props while omitting those already covered by ButtonProps, allowing the addition of custom props like height. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { Button, ButtonProps, ElementProps } from '@mantine/core';

interface MyButtonProps
  extends ButtonProps,
    ElementProps<'button', keyof ButtonProps> {
  height: number;
}

function MyButton({ height, ...others }: MyButtonProps) {
  return <Button style={{ height }} {...others} />;
}

TITLE: Validating List Fields with Superstruct and useForm DESCRIPTION: This snippet demonstrates validating list fields using Superstruct with Mantine Form. It defines a Superstruct schema that validates the properties within each item in the list. The example demonstrates how to access the error messages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_11

LANGUAGE: tsx CODE:

import { superstructResolver } from 'mantine-form-superstruct-resolver';
import * as s from 'superstruct';
import { useForm } from '@mantine/form';

const listSchema = s.object({
  list: s.array(
    s.object({
      name: s.size(s.string(), 2, 30),
    })
  ),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    list: [{ name: '' }],
  },
  validate: superstructResolver(listSchema),
});

form.validate();
form.errors;
// -> {
//  'list 0 name: Expected a string with a length between `2` and `30` but received one with a length of `0`',
// }

TITLE: Using leftSection and rightSection on Mantine Button (TSX) DESCRIPTION: This example illustrates the usage of the new leftSection and rightSection props available on Mantine components like Button. These props replace the older icon and rightSection props, allowing content to be placed on either side of the main label. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-0-0.mdx#_snippet_7

LANGUAGE: tsx CODE:

import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button leftSection="left" rightSection="right">
      Label
    </Button>
  );
}

TITLE: Controlling Popover State with onDismiss (TSX) DESCRIPTION: Demonstrates how to use the onDismiss prop with a controlled Popover component to manage its open state while still allowing closure via outside clicks and the Escape key. It uses React's useState hook to control the opened prop. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/popover.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Button, Popover } from '@mantine/core';

function Demo() {
  const [opened, setOpened] = useState(false);
  return (
    <Popover
      opened={opened}
      onDismiss={() => setOpened(false)}
    >
      <Popover.Target>
        <Button onClick={() => setOpened((o) => !o)}>
          Toggle popover
        </Button>
      </Popover.Target>

      <Popover.Dropdown>Dropdown</Popover.Dropdown>
    </Popover>
  );
}

TITLE: Example Mantine Sass Module Usage DESCRIPTION: Demonstrates how to utilize the global Mantine Sass resources (_mantine.scss) within a component-level Sass module file. It shows using the rem function for sizing, applying color scheme specific styles with @include mantine.light and @include mantine.dark, and creating responsive styles with @include mantine.smaller-than using defined breakpoint variables. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/sass.mdx#_snippet_2

LANGUAGE: scss CODE:

// example.module.scss
.title {
  // light-dark function is handled by PostCSS
  color: light-dark(
    var(--mantine-color-black),
    var(--mantine-color-white)
  );
  font-size: mantine.rem(100px);
  font-weight: 900;
  letter-spacing: mantine.rem(-2px);

  @include mantine.light {
    background-color: red;
  }

  @include mantine.dark {
    background-color: blue;
  }

  @include mantine.smaller-than(mantine.$mantine-breakpoint-md) {
    font-size: mantine.rem(50px);
  }
}

TITLE: Configuring Anchor Default Props - TypeScript DESCRIPTION: This TypeScript snippet demonstrates how to configure the underline prop for all Anchor components globally using the Mantine theme. It creates a custom theme and extends the Anchor component's default props to set underline to always. This means all Anchor components within the MantineProvider will have the underline style applied. It uses createTheme to define the new theme and MantineProvider to apply the theme to the application. It requires the @mantine/core dependency. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/anchor.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { Anchor, createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  components: {
    Anchor: Anchor.extend({
      defaultProps: {
        underline: 'always',
      },
    }),
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}


TITLE: Validating Nested Fields with Joi and useForm DESCRIPTION: This snippet shows the validation of nested fields with Joi and Mantine Form. It defines a Joi schema for a nested object, integrates with the useForm hook using joiResolver, and demonstrates access to validation error messages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_7

LANGUAGE: tsx CODE:

import Joi from 'joi';
import { joiResolver } from 'mantine-form-joi-resolver';
import { useForm } from '@mantine/form';

const nestedSchema = Joi.object({
  nested: Joi.object({
    field: Joi.string().min(2).messages({
      'string.min': 'Field should have at least 2 letters',
      'string.empty': 'Field should have at least 2 letters',
    }),
  }),
});
const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    nested: {
      field: '',
    },
  },
  validate: joiResolver(nestedSchema),
});

form.validate();
form.errors;
// -> {
//  'nested.field': 'Field should have at least 2 letters',
// }

TITLE: Implementing Nested Valibot Schema Validation in Mantine Form (TSX) DESCRIPTION: Demonstrates how to use valibotResolver with a Valibot schema that includes nested objects to validate nested fields within a Mantine form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-4-0.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver';
import { minLength, object, string } from 'valibot';
import { useForm } from '@mantine/form';

const nestedSchema = object({
  nested: object({
    field: string([
      minLength(2, 'Field should have at least 2 letters'),
    ]),
  }),
});

const form = useForm({
  initialValues: {
    nested: {
      field: '',
    },
  },
  validate: valibotResolver(nestedSchema),
});

form.validate();
form.errors;
// -> {
//  'nested.field': 'Field should have at least 2 letters',
// }

TITLE: Example of passing callback function as children without 'use client' directive DESCRIPTION: This snippet demonstrates an error scenario where a callback function is passed as children to a Mantine CopyButton component in a server component, which is invalid. It highlights the need to add 'use client' for such cases. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_2

LANGUAGE: TypeScript CODE:

// ❌ This will throw an error
import { CopyButton } from '@mantine/core';

function Demo() {
  return (
    <CopyButton value="https://mantine.dev">
      {({ copied, copy }) => (
        <button color={copied ? 'teal' : 'blue'} onClick={copy}>
          {copied ? 'Copied url' : 'Copy url'}
        </button>
      )}
    </CopyButton>
  );
}

TITLE: Making a Standard Mantine Component Polymorphic (TSX) DESCRIPTION: Demonstrates how to add polymorphic type support to a standard Mantine component (like Group) that accepts the component prop but doesn't have polymorphic types by default. This is achieved using the createPolymorphicComponent utility function from @mantine/core, improving type safety when changing the root element. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/polymorphic.mdx#_snippet_7

LANGUAGE: tsx CODE:

import {
  createPolymorphicComponent,
  Group,
  GroupProps,
} from '@mantine/core';

const PolymorphicGroup = createPolymorphicComponent<
  'button',
  GroupProps
>(Group);

function Demo() {
  return (
    <PolymorphicGroup component="a" href="https://mantine.dev" />
  );
}

TITLE: Migrating styles prop with nested selectors DESCRIPTION: Shows how to migrate from styles prop with nested selectors in 6.x to CSS Modules in 7.x for component customization. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/6x-to-7x.mdx#_snippet_6

LANGUAGE: tsx CODE:

// 6.x – nested selectors
import { TextInput } from '@mantine/core';

function Demo() {
  return (
    <TextInput
      styles={{
        input: {
          '&:focus': {
            color: 'red',
          },
        },
      }}
    />
  );
}

LANGUAGE: scss CODE:

/* 7.0 */
.input {
  &:focus {
    color: red;
  }
}

TITLE: Using Autocomplete with String Array Data in TypeScript DESCRIPTION: Demonstrates how to implement the Autocomplete component from Mantine with a simple string array passed to the data prop, allowing users to either select listed options or freely enter any string value. This snippet has no dependencies besides mantine/core. The input is a string array and output is user selection or input as a string. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/autocomplete-value-label.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { Autocomplete } from '@mantine/core';

function Demo() {
  return <Autocomplete data={["React", "Vue"]} />;
}

TITLE: Using mod prop to add data attributes on Mantine components in TypeScript DESCRIPTION: Provides examples of the new universal 'mod' prop that attaches data-* attributes to the root element of Mantine components. This feature supports string, object, and array formats to define multiple or conditional attributes. This approach facilitates adding semantic data attributes for styling or automation without modifying DOM directly. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.5.0.md#_snippet_8

LANGUAGE: tsx CODE:

import { Box } from '@mantine/core';

<Box mod="data-button" />;
// -> <div data-button />

<Box mod={{ opened: true }} />;
// -> <div data-opened />

<Box mod={{ opened: false }} />;
// -> <div />

<Box mod={["button", { opened: true }]} />;
// -> <div data-button data-opened />

<Box mod={{ orientation: 'horizontal' }} />;
// -> <div data-orientation="horizontal" />

TITLE: Creating Custom Select with Mantine Combobox in TSX DESCRIPTION: Shows how to use the Combobox component from @mantine/core to build a custom select input with options and state management. Requires @mantine/core and React useState hook. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_26

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Combobox, Input, InputBase, useCombobox } from '@mantine/core';

const groceries = ['🍎 Apples', '🍌 Bananas', '🥦 Broccoli', '🥕 Carrots', '🍫 Chocolate'];

function Demo() {
  const combobox = useCombobox({
    onDropdownClose: () => combobox.resetSelectedOption(),
  });

  const [value, setValue] = useState<string | null>(null);

  const options = groceries.map((item) => (
    <Combobox.Option value={item} key={item}>
      {item}
    </Combobox.Option>
  ));

  return (
    <Combobox
      store={combobox}
      onOptionSubmit={(val) => {
        setValue(val);
        combobox.closeDropdown();
      }}
    >
      <Combobox.Target>
        <InputBase
          component="button"
          pointer
          rightSection={<Combobox.Chevron />}
          onClick={() => combobox.toggleDropdown()}
        >
          {value || <Input.Placeholder>Pick value</Input.Placeholder>}
        </InputBase>
      </Combobox.Target>

      <Combobox.Dropdown>
        <Combobox.Options>{options}</Combobox.Options>
      </Combobox.Dropdown>
    </Combobox>
  );
}

TITLE: Applying Responsive Width with Mantine Box (TSX) DESCRIPTION: Demonstrates how to use the w style prop with object syntax to apply responsive width values to a Mantine Box component based on theme breakpoints. The width changes at sm and lg breakpoints. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/responsive.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { Box } from '@mantine/core';

function Demo() {
  return <Box w={{ base: 320, sm: 480, lg: 640 }} />;
}

TITLE: Modal Component with Customizable Options DESCRIPTION: Demonstrates the implementation of the Modal component with varying customizations for different features like removing header, changing size, or customizing the overlay and transitions. The code snippets demonstrate various props like withCloseButton, size, overlayProps, transitionProps, etc. which provide flexibility and control over the modal's appearance and behavior. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/modal.mdx#_snippet_2

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.usage} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.centered} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.header} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.sizes} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.sizeAuto} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.fullScreen} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.fullScreenMobile} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.overlay} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.overflow} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.scrollarea} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.offset} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.transitions} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.transitionEnd} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.initialFocus} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.initialFocusTrap} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.closeIcon} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.composition} />

LANGUAGE: JSX CODE:

<Demo data={ModalDemos.stack} />

TITLE: ColorSwatch Polymorphic Component Demo DESCRIPTION: Shows how to use ColorSwatch as a polymorphic component, changing it from the default div element to a button element. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/color-swatch.mdx#_snippet_3

LANGUAGE: JSX CODE:

<Polymorphic
  defaultElement="div"
  changeToElement="button"
  component="ColorSwatch"
/>

TITLE: Assigning Non-Memoized Handler Refs with assignRef Utility (TypeScript) DESCRIPTION: This snippet demonstrates how to use Mantine's assignRef utility to assign function handler refs that are not memoized via useCallback. The example defines a NumberInputHandlers interface, a DemoProps interface for an optional forwarded ref, and a Demo component that assigns a custom handler object to the provided ref. Dependencies: react, @mantine/hooks. Inputs are handler refs; output is a handlers object with increment and decrement functions. This is usually used for exposing imperative handlers instead of element refs. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-merged-ref.mdx#_snippet_2

LANGUAGE: TSX CODE:

import { useState } from 'react';
import { assignRef } from '@mantine/hooks';

interface NumberInputHandlers {
  increment: () => void;
  decrement: () => void;
}

interface DemoProps {
  handlersRef?: React.ForwardedRef<NumberInputHandlers | undefined>;
}

function Demo({ handlersRef }: DemoProps) {
  const [value, setValue] = useState(0);

  const increment = () => setValue((v) => v + 1);
  const decrement = () => setValue((v) => v - 1);

  assignRef(handlersRef, { increment, decrement });

  return (
    <>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </>
  );
}

TITLE: Setting DatePicker Navigation Aria Labels (tsx) DESCRIPTION: Demonstrates how to use the ariaLabels prop to customize the aria-label attributes for the next/previous decade, year, and month controls, as well as the controls to change view level (year/month). This improves accessibility for users relying on screen readers. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/date-picker.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { DatePicker } from '@mantine/dates';

function Demo() {
  return (
    <DatePicker
      ariaLabels={{
        nextDecade: 'Next decade',
        previousDecade: 'Previous decade',
        nextYear: 'Next year',
        previousYear: 'Previous year',
        nextMonth: 'Next month',
        previousMonth: 'Previous month',
        yearLevelControl: 'Change to decade view',
        monthLevelControl: 'Change to year view',
      }}
    />
  );
}

TITLE: Adding Accessibility Labels to Mantine Slider Thumbs (TSX) DESCRIPTION: Shows how to add accessibility labels (thumbLabel, thumbFromLabel, thumbToLabel) to Mantine Slider and RangeSlider thumbs for improved screen reader support. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/slider.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { RangeSlider, Slider } from '@mantine/core';

function Demo() {
  return (
    <>
      <Slider thumbLabel="Thumb aria-label" />
      <RangeSlider
        thumbFromLabel="First thumb aria-label"
        thumbToLabel="Second thumb aria-label"
      />
    </>
  );
}

TITLE: Setting Submitting State Manually DESCRIPTION: This snippet shows how to manually set and check the form.submitting state. form.submitting can be set to true or false using form.setSubmitting(). The code depends on @mantine/form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/status.mdx#_snippet_5

LANGUAGE: tsx CODE:

```tsx
import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled' });
form.submitting; // -> false

form.setSubmitting(true);
form.submitting; // -> true

form.setSubmitting(false);
form.submitting; // -> false

----------------------------------------

TITLE: Using Mantine z-index CSS Variables (CSS)
DESCRIPTION: Demonstrates how to use Mantine's new z-index CSS custom properties to control layering. This snippet places .my-content above a modal by calculating z-index based on the --mantine-z-index-modal variable. Requires Mantine's CSS variables present in the document.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.3.0.md#_snippet_13

LANGUAGE: css
CODE:

/* Display content above the modal */ .my-content { z-index: calc(var(--mantine-z-index-modal) + 1); }


----------------------------------------

TITLE: Customizing Mantine Input Size with data-size (TSX)
DESCRIPTION: This snippet shows how to use Mantine's `createTheme` and `Input.extend` to apply custom CSS classes (`Demo.module.css`) to the `Input` component based on its `size` prop, which is rendered as a `data-size` attribute. It requires a corresponding CSS module file.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_8

LANGUAGE: tsx
CODE:

import { createTheme, Input, MantineProvider } from '@mantine/core'; import classes from './Demo.module.css';

const theme = createTheme({ components: { Input: Input.extend({ classNames: classes }), }, });

function Demo() { return ( <MantineProvider theme={theme}> <Input placeholder="Size XXL" size="xxl" /> <Input placeholder="Size XXS" size="xxs" mt="md" /> </MantineProvider> ); }


----------------------------------------

TITLE: Importing Mantine Styles with CSS Layers (TSX)
DESCRIPTION: Shows how to import Mantine styles using the new .layer.css files. Explains that styles imported this way are placed in a CSS layer, affecting their cascade order relative to styles not in a layer. Includes a comment about local CSS modules.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-1-0.mdx#_snippet_0

LANGUAGE: tsx
CODE:

// If your styles are not wrapped in @layer directive, // they will be applied after Mantine styles. // Import order does not affect styles in this case import classes from './Demo.module.css';

import '@mantine/core/styles.layer.css';


----------------------------------------

TITLE: Changing Body Background Color with Mantine CSS Variables
DESCRIPTION: A more integrated approach using Mantine's CSS variables to change the body background color. This method defines different background colors for light and dark themes, affecting both the body and components that use the same variable.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/body-background.mdx#_snippet_1

LANGUAGE: scss
CODE:

:root { @mixin light-root { --mantine-color-body: #f9f9f9; }

@mixin dark-root { --mantine-color-body: #333; } }


----------------------------------------

TITLE: Handling List Fields in Uncontrolled Forms
DESCRIPTION: Demonstration of correct and incorrect ways to handle arrays of form fields in uncontrolled mode, using wrapper elements for key management.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/uncontrolled.mdx#_snippet_5

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form'; import { randomId } from '@mantine/hooks';

// ❌ Incorrect: Do not override key prop, even in lists function Demo() { const form = useForm({ mode: 'uncontrolled', initialValues: { jobs: [{ company: 'Google' }, { company: 'Facebook' }], }, });

const fields = form.getValues().jobs.map((_, index) => ( <input {...form.getInputProps(jobs.${index}.company)} key={index} /> ));

return <form>{fields}</form>; }

// ✅ Correct: Add wrapper element and pass key to it function Demo() { const form = useForm({ mode: 'uncontrolled', initialValues: { jobs: [ { company: 'Google', key: randomId() }, { company: 'Facebook', key: randomId() }, ], }, });

const fields = form.getValues().jobs.map((item, index) => ( <div key={item.key}> <input {...form.getInputProps(jobs.${index}.company)} key={form.key(jobs.${index}.company)} /> </div> ));

return <form>{fields}</form>; }


----------------------------------------

TITLE: Prepending Items to a List with useListState
DESCRIPTION: The `prepend` handler adds one or more items to the beginning of the list. The provided item(s) are inserted at the start of the list. This snippet shows how to prepend items with `a: 3` and `a: 4` to the list.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-list-state.mdx#_snippet_2

LANGUAGE: tsx
CODE:

// add one or more items to the start of the list const prepend = () => handlers.prepend({ a: 3 }, { a: 4 }); // values -> [{ a: 3 }, { a: 4 }, { a: 1 }, { a: 2 }]


----------------------------------------

TITLE: Integrating Mantine and Emotion Providers in Next.js Root Layout (React/TypeScript)
DESCRIPTION: The root layout component (`app/layout.tsx`) wraps the entire application content with the necessary providers for Mantine and Emotion. It includes the custom `RootStyleRegistry` for SSR, `MantineEmotionProvider`, and `MantineProvider` with the `emotionTransform`. This setup ensures that Mantine components and Emotion styling work correctly throughout the application. It requires importing Mantine core styles and components, as well as the custom registry component.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_10

LANGUAGE: tsx
CODE:

import '@mantine/core/styles.css';

import { ColorSchemeScript, MantineProvider } from '@mantine/core'; import { emotionTransform, MantineEmotionProvider, } from '@mantine/emotion'; import { RootStyleRegistry } from './EmotionRootStyleRegistry';

export const metadata = { title: 'Mantine Next.js template', description: 'I am using Mantine with Next.js!', };

export default function RootLayout({ children }: { children: any }) { return ( <html lang="en"> <head> <ColorSchemeScript /> <link rel="shortcut icon" href="/favicon.svg" /> <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, user-scalable=no" /> </head> <body> <RootStyleRegistry> <MantineEmotionProvider> <MantineProvider stylesTransform={emotionTransform}> {children} </MantineProvider> </MantineEmotionProvider> </RootStyleRegistry> </body> </html> ); }


----------------------------------------

TITLE: Selective Validation on Blur for Specific Fields with Mantine useForm in TypeScript
DESCRIPTION: Allows validation only on specific fields when they lose focus by assigning an array of field paths to validateInputOnBlur. Supports nested fields using the FORM_INDEX constant. Improves user experience by limiting validation to relevant fields only. Depends on '@mantine/form' and FORM_INDEX. Inputs: form settings and field paths; output: form object configured for selective blur validation.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validation.mdx#_snippet_4

LANGUAGE: tsx
CODE:

import { FORM_INDEX, useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', validateInputOnBlur: ['name', 'email', jobs.${FORM_INDEX}.title], });


----------------------------------------

TITLE: Selective Live Validation for Specific Fields with Mantine useForm in TypeScript
DESCRIPTION: Sets up the form to validate only specified fields on input changes by providing an array of field paths to the validateInputOnChange option. Demonstrates usage of a dynamic index constant FORM_INDEX for nested arrays. This approach improves performance by limiting validation scope. Depends on '@mantine/form' and a constant FORM_INDEX. Inputs are the form configuration and specific field paths; output is a form object with scoped live validation.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validation.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import { FORM_INDEX, useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', validateInputOnChange: [ 'name', 'email', jobs.${FORM_INDEX}.title, ], });


----------------------------------------

TITLE: Handling Dynamic Component Prop Types (TSX)
DESCRIPTION: Illustrates two approaches for using a dynamic value (e.g., based on a condition) in the `component` prop of a polymorphic Mantine `Box` component. Type checking can be maintained by providing explicit types (`<'input'>`) and casting the dynamic value to `any`, or disabled entirely by passing `any` as the type argument (`<any>`).
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/polymorphic.mdx#_snippet_6

LANGUAGE: tsx
CODE:

import { Box } from '@mantine/core';

function KeepTypes() { return ( <Box<'input'> component={(Math.random() > 0.5 ? 'input' : 'div') as any} /> ); }

function NukeTypes() { return ( <Box<any> component={Math.random() > 0.5 ? 'input' : 'div'} /> ); }


----------------------------------------

TITLE: Enabling Tree Shaking with Next.js App Router
DESCRIPTION: Configures experimental Next.js feature 'optimizePackageImports' in next.config.mjs to optimize imports and support tree shaking for Mantine components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/next.mdx#_snippet_10

LANGUAGE: JavaScript
CODE:

export default { // ...other configuration experimental: { optimizePackageImports: ['@mantine/core', '@mantine/hooks'], }, };


----------------------------------------

TITLE: Accessing Form Errors with useForm – Mantine
DESCRIPTION: Demonstrates how to access the `form.errors` object after validation. Initially, the errors object is empty. After manual validation, it contains validation error messages for each field.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/errors.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { firstName: '', lastName: '' }, validate: { firstName: (value) => value.length < 2 ? 'First name is too short' : null, lastName: (value) => value.length < 2 ? 'Last name is too short' : null, }, });

// Errors object is empty by default form.errors; // -> {}

// Errors will be filled when you call form.validate manually // or automatically with form.onSubmit handler form.validate();

form.errors; // -> // { // firstName: 'First name is too short', // lastName: 'Last name is too short' // }


----------------------------------------

TITLE: Rendering Date Range Selection Demo for DatePickerInput in JSX
DESCRIPTION: Shows a demo of setting the `type` prop to "range" enabling users to pick a range of dates. This demonstrates the component's ability to handle date-range selections visually and interactively.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/date-picker-input.mdx#_snippet_4

LANGUAGE: JSX
CODE:
<Demo data={DatePickerInputDemos.range} /> ```

TITLE: Using Form Context from a Separate File - Child Component DESCRIPTION: Example of importing and using the form context in a child component to create a form input field that accesses the shared form state. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/create-form-context.mdx#_snippet_2

LANGUAGE: tsx CODE:

// NameInput.tsx
import { TextInput } from '@mantine/core';
import { useUserFormContext } from './form-context';

export function NameInput() {
  const form = useUserFormContext();
  return (
    <TextInput
      label="Name"
      key={form.key('name')}
      {...form.getInputProps('name')}
    />
  );
}

TITLE: Configuring Mantine Theme for REM Scaling (TSX) DESCRIPTION: This snippet shows how to use createTheme to set the scale property in the Mantine theme. The scale value (e.g., 1.6) is calculated based on the desired root font size (e.g., 10px) relative to the default 16px, ensuring Mantine components scale correctly. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_12

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  scale: 1.6,
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      <App />
    </MantineProvider>
  );
}

TITLE: Reading local storage value with default hook behavior in TypeScript DESCRIPTION: This snippet demonstrates the usage of Mantine's useLocalStorage hook in a React component, fetching a color scheme value ('light' or 'dark') that initializes from local storage after component mounts to prevent hydration issues. Dependencies include '@mantine/hooks'. The hook returns a state variable 'value' and a setter 'setValue', with default value 'dark'. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/local-storage-effect.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

import { useLocalStorage } from '@mantine/hooks';

function Demo() {
  const [value, setValue] = useLocalStorage<'light' | 'dark'>({
    key: 'color-scheme',
    defaultValue: 'dark',
  });

  return <div>{value}</div>;
}

TITLE: Scaling Mantine Components with Theme (CSS, TSX) DESCRIPTION: Demonstrates how to configure the Mantine theme with the scale property to adjust component sizes proportionally when the root font size has been changed. The scale value is calculated based on the desired root font size relative to the default 16px. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-0-0.mdx#_snippet_4

LANGUAGE: css CODE:

:root {
  font-size: 10px;
}

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  scale: 1.6,
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Use Mantine Hidden/Visible Classes (TSX) DESCRIPTION: Demonstrates how to use the utility classes mantine-hidden-from-{breakpoint} and mantine-visible-from-{breakpoint} to conditionally hide or show elements based on viewport width. This is useful for custom components or when not using Mantine components directly. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/responsive.mdx#_snippet_4

LANGUAGE: tsx CODE:

function CustomComponent() {
  return (
    <>
      <div className="mantine-hidden-from-md">Hidden from md</div>
      <div className="mantine-visible-from-xl">Visible from xl</div>
    </>
  );
}

TITLE: useDebouncedCallback Definition – TypeScript DESCRIPTION: Defines the structure and type signature for the useDebouncedCallback hook. It accepts a callback function and a delay as input, returning a debounced version of the callback. The debounced function will only be executed after the specified delay has passed since the last invocation. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-debounced-callback.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

function useDebouncedCallback<T extends (...args: any[]) => any>(
  callback: T,
  delay: number
): (...args: Parameters<T>) => void;

TITLE: Polymorphic Component Example DESCRIPTION: Illustrates how to use the Polymorphic component to change the underlying HTML element of the Paper component. The defaultElement is 'div' which can be changed to 'button'. withNext is likely a prop used by the Polymorphic component or its children. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/paper.mdx#_snippet_5

LANGUAGE: mdx CODE:

<Polymorphic
  defaultElement="div"
  changeToElement="button"
  component="Paper"
  withNext
/>

TITLE: Enabling Live Validation on Input Change with Mantine useForm in TypeScript DESCRIPTION: Configures the form to perform validation on every input change event by setting the validateInputOnChange option to true. This allows immediate feedback while typing. The form is initialized in uncontrolled mode with this live validation behavior. Requires '@mantine/form'. Inputs: form configuration object; Outputs: form instance with live validation enabled. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validation.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  validateInputOnChange: true,
});

TITLE: Apply ClassNames Conditionally Based on Props (TSX/SCSS) DESCRIPTION: Shows how to access component props within the classNames function when using Component.extend. This enables conditional application of CSS classes based on prop values (e.g., required, error), offering a powerful replacement for stylesParams. Includes the corresponding SCSS styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_5

LANGUAGE: tsx CODE:

import cx from 'clsx';
import { createTheme, MantineProvider, TextInput } from '@mantine/core';
import classes from './Demo.module.css';

const theme = createTheme({
  components: {
    TextInput: TextInput.extend({
      classNames: (_theme, props) => ({
        label: cx({ [classes.labelRequired]: props.required }),
        input: cx({ [classes.inputError]: props.error }),
      }),
    }),
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      <TextInput required label="Required input" placeholder="Required input" />
      <TextInput error label="Input with error" placeholder="Input with error" mt="md" />
    </MantineProvider>
  );
}

LANGUAGE: scss CODE:

.labelRequired {
  color: var(--mantine-color-red-filled);
}

.inputError {
  background-color: var(--mantine-color-red-light);
}

TITLE: Setting Accessibility Labels for Mantine TimePicker (TSX) DESCRIPTION: Shows how to improve the accessibility of the Mantine TimePicker by setting ARIA labels for the individual hour, minute, second, and AM/PM inputs using hoursInputLabel, minutesInputLabel, secondsInputLabel, and amPmInputLabel props. Also demonstrates setting an ARIA label for the clear button using clearButtonProps. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/time-picker.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { TimePicker } from '@mantine/dates';

function Demo() {
  return (
    <TimePicker
      hoursInputLabel="Hours"
      minutesInputLabel="Minutes"
      secondsInputLabel="Seconds"
      amPmInputLabel="AM/PM"
      clearButtonProps={{ 'aria-label': 'Clear time' }}
    />
  );
}

TITLE: Setting Aria Labels for YearPicker Navigation (TSX) DESCRIPTION: This example shows how to customize the aria-label attributes for the next and previous decade navigation controls within the Mantine YearPicker component using the ariaLabels prop. This improves accessibility by providing descriptive labels for screen reader users. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/year-picker.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { YearPicker } from '@mantine/dates';

function Demo() {
  return (
    <YearPicker
      ariaLabels={{
        nextDecade: 'Next decade',
        previousDecade: 'Previous decade',
      }}
    />
  );
}

TITLE: Setting Aria Labels for MonthPicker Controls (tsx) DESCRIPTION: Demonstrates how to use the ariaLabels prop to set custom aria-label attributes for the next/previous decade and year controls, as well as the year level control in the Mantine MonthPicker component. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/month-picker.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { MonthPicker } from '@mantine/dates';

function Demo() {
  return (
    <MonthPicker
      ariaLabels={{
        nextDecade: 'Next decade',
        previousDecade: 'Previous decade',
        nextYear: 'Next year',
        previousYear: 'Previous year',
        yearLevelControl: 'Change to decade view',
      }}
    />
  );
}

TITLE: Integrating Mantine Button with Next.js Link (>= v13) (TSX) DESCRIPTION: Demonstrates the integration of a Mantine Button with Next.js Link for versions 13 and above. The Link component is directly passed to the component prop of the Button, simplifying the integration compared to older Next.js versions. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/polymorphic.mdx#_snippet_3

LANGUAGE: tsx CODE:

import Link from 'next/link';
import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button component={Link} href="/hello">
      Next link button
    </Button>
  );
}

TITLE: Disabling specific options in dropdown DESCRIPTION: This code illustrates how to disable certain options so they cannot be selected while still allowing user input of disabled options, with recommended filtering in onChange handler for strict control. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tags-input.mdx#_snippet_12

LANGUAGE: TypeScript CODE:

<Demo data={TagsInputDemos.disabledOptions} />

TITLE: Using form actions in external components DESCRIPTION: Shows how to use form actions to manipulate form state from components that don't have direct access to the form. Examples include setting values from API responses and resetting the form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/actions.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { useEffect } from 'react';
import { Button } from '@mantine/core';
import { demoFormActions } from './demoFormActions';

function ExternalComponent() {
  useEffect(() => {
    fetch('/api/user')
      .then((res) => res.json())
      .then((res) =>
        demoFormActions.setValues({
          name: res.name,
          age: res.age,
        })
      );
  }, []);

  return (
    <Button onClick={() => demoFormActions.reset()}>
      Reset demo form
    </Button>
  );
}

TITLE: Managing Form Validation Errors - Mantine (TypeScript/TSX) DESCRIPTION: This snippet details the use of error manipulation methods within a useForm instance, such as reading, setting, and clearing error messages for entire forms or individual fields. No additional dependencies are required. Inputs include error objects or messages and target field paths; output is an updated form.errors state. These utilities are typically used alongside custom validation or UI error feedback handling. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_4

LANGUAGE: TSX CODE:

// get current errors state
form.errors;

// Set all errors
form.setErrors({ path: 'Error message', path2: 'Another error' });

// Set error message at specified path
form.setFieldError('user.lastName', 'No special characters allowed');

// Clears all errors
form.clearErrors();

// Clears error of field at specified path
form.clearFieldError('path');

TITLE: Rendering accessible Mantine Progress components with aria attributes in TSX DESCRIPTION: Provides example implementations of the Mantine Progress component emphasizing accessibility using ARIA attributes such as aria-label, role="progressbar", aria-valuemin, aria-valuemax, and aria-valuenow. Demonstrates both a simple Progress component and a compound component approach with Progress.Root and Progress.Section. Requires @mantine/core installed and relevant imports. The value prop indicates the progress percentage, and aria-label provides a textual label for screen readers. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/progress.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { Progress } from '@mantine/core';

function Demo() {
  return <Progress aria-label="Uploading progress" value={10} />;
}

function DemoCompound() {
  return (
    <Progress.Root>
      <Progress.Section aria-label="Uploading progress" value={10} />
    </Progress.Root>
  );
}

TITLE: CSS usage of alpha, lighten, and darken functions with CSS variables in SCSS DESCRIPTION: Provides examples of CSS styling using 'alpha', 'lighten', and 'darken' functions in SCSS files with CSS variables from Mantine. It shows how these functions transform to CSS 'color-mix' expressions on older CSS preprocessor stages, allowing dynamic color manipulation at the stylesheet level. Requires postcss-preset-mantine version 1.12.0 or higher for automatic transformations. Enables use of advanced color models in CSS rather than fixed values. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_8

LANGUAGE: scss CODE:

.demo-alpha {
  color: alpha(var(--mantine-color-red-4), 0.5);
  border: 1px solid alpha(#ffc, 0.2);
}

.demo-lighten-darken {
  color: lighten(var(--mantine-color-red-4), 0.5);
  border: 1px solid darken(#ffc, 0.2);
}

TITLE: Using Mantine usePagination Hook DESCRIPTION: Demonstrates basic initialization and usage of the usePagination hook in an uncontrolled state. It shows how to access the calculated range property and call various methods like setPage, next, previous, last, and first to navigate pages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-pagination.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { usePagination } from '@mantine/hooks';

const pagination = usePagination({ total: 10, initialPage: 1 });

pagination.range; // -> [1, 2, 3, 4, 5, 'dots', 10];

pagination.setPage(5);
pagination.range; // -> [1, 'dots', 4, 5, 6, 'dots', 10];

pagination.next();
pagination.range; // -> [1, 'dots', 5, 6, 7, 'dots', 10];

pagination.previous();
pagination.range; // -> [1, 'dots', 4, 5, 6, 'dots', 10];

pagination.last();
pagination.range; // -> [1, 'dots', 6, 7, 8, 9, 10];

pagination.first();
pagination.range; // -> [1, 2, 3, 4, 5, 'dots', 10];

TITLE: Implementing a Color Scheme Toggle with useLocalStorage in React DESCRIPTION: Example of creating a color scheme toggle button component that uses the useLocalStorage hook to persist the user's color scheme preference across page reloads. The component toggles between light and dark themes and displays the appropriate icon. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-local-storage.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { IconMoonStars, IconSun } from '@tabler/icons-react';
import { ActionIcon } from '@mantine/core';
import { useLocalStorage } from '@mantine/hooks';

function ColorSchemeToggle() {
  const [colorScheme, setColorScheme] = useLocalStorage<
    'light' | 'dark'
  >({
    key: 'color-scheme',
    defaultValue: 'light',
  });

  const toggleColorScheme = () =>
    setColorScheme((current) =>
      current === 'dark' ? 'light' : 'dark'
    );

  return (
    <ActionIcon onClick={toggleColorScheme}>
      {colorScheme === 'dark' ? <IconSun /> : <IconMoonStars />}
    </ActionIcon>
  );
}

TITLE: Implementing useElementSize Hook in React/TypeScript DESCRIPTION: Demonstrates the basic usage of the useElementSize hook. It shows how to import the hook from @mantine/hooks and destructure the returned ref, width, and height. The ref should be attached to the target DOM element whose dimensions are needed. Initially, or when no element is observed, width and height will be 0. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-element-size.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useElementSize } from '@mantine/hooks';

const { ref, width, height } = useElementSize();

TITLE: Defining Vitest Scripts in package.json (JSON) DESCRIPTION: This snippet provides an example scripts block in package.json for running Vitest tests from the CLI or with watch mode. The vitest script runs the entire suite, while vitest:watch runs Vitest in watch mode. It's essential for facilitating test runs and should be added to the project's package.json file. Requires Vitest as a dev dependency. No configuration parameters are required beyond what is shown. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/vitest.mdx#_snippet_2

LANGUAGE: JSON CODE:

{
  "scripts": {
    "vitest": "vitest run",
    "vitest:watch": "vitest"
  }
}

TITLE: Enabling Validation on Input Blur with Mantine useForm in TypeScript DESCRIPTION: Configures the form to validate all fields when inputs lose focus by setting the validateInputOnBlur option to true. This defers validation feedback until user finishes editing a field. Requires '@mantine/form'. Input: form configuration; output: form instance with blur-triggered validation. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validation.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  validateInputOnBlur: true,
});

TITLE: Initializing useFocusTrap Hook in React with TypeScript DESCRIPTION: This snippet shows how to initialize the useFocusTrap hook within a React functional component. The hook returns a ref which should be assigned to the container element that requires focus trapping, such as modals or menus containing focusable elements. It ensures keyboard navigation focus cycles within this node. No parameters are passed, so the trap defaults to inactive. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-focus-trap.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useFocusTrap } from '@mantine/hooks';

function Demo() {
  const focusTrapRef = useFocusTrap();

  return (
    <div ref={focusTrapRef}>
      <input />
    </div>
  );
}

TITLE: Importing NProgress Styles – TSX DESCRIPTION: Imports the required CSS styles for the @mantine/nprogress package. These styles are essential for the visual representation of the navigation progress bar. This import should be done at the root of the application to ensure styles are applied globally. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/nprogress.mdx#_snippet_0

LANGUAGE: tsx CODE:

import '@mantine/nprogress/styles.css';

TITLE: Using Mantine Dropzone Grouped Mime Types Constant (TSX) DESCRIPTION: Shows how to accept common groups of mime types using predefined constants like 'IMAGE_MIME_TYPE' exported from '@mantine/dropzone'. This simplifies accepting broad categories of files with a single constant. 'onDrop' is a required prop. Requires importing the specific group constant. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/dropzone.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { Dropzone, IMAGE_MIME_TYPE } from '@mantine/dropzone';

function Demo() {
  return (
    <Dropzone accept={IMAGE_MIME_TYPE} onDrop={() => {}}>
      {/* children */}
    </Dropzone>
  );
}


TITLE: Using onValuesChange Callback for Form Value Changes DESCRIPTION: Proper way to observe form value changes using the onValuesChange callback instead of useEffect with form values. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/uncontrolled.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { name: 'John Doe' },
  onValuesChange: (values) => {
    // ✅ This will be called on every form values change
    console.log(values);
  },
});

TITLE: Creating Table of Contents with TableOfContents Component in TypeScript React DESCRIPTION: Shows usage of the TableOfContents component in Mantine, which is built on the use-scroll-spy hook to automatically create a table of contents UI based on heading elements. It supports properties such as variant, color, size, and radius for styling, as well as scrollSpyOptions to define which elements to spy on. The getControlProps function handles scroll behavior when clicking TOC items. Requires React and @mantine/core package. Outputs a styled, interactive table of contents that scrolls to relevant sections. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.16.0.md#_snippet_1

LANGUAGE: tsx CODE:

import { TableOfContents } from '@mantine/core';

function Demo() {
  return (
    <TableOfContents
      variant="filled"
      color="blue"
      size="sm"
      radius="sm"
      scrollSpyOptions={{
        selector: '#mdx :is(h1, h2, h3, h4, h5, h6)',
      }}
      getControlProps={({ data }) => ({
        onClick: () => data.getNode().scrollIntoView(),
        children: data.value,
      })}
    />
  );
}

TITLE: Local Storage Color Scheme Manager (TSX) DESCRIPTION: Provides a factory function localStorageColorSchemeManager that creates a MantineColorSchemeManager instance using browser local storage, allowing customization of the storage key. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/color-schemes.mdx#_snippet_7

LANGUAGE: tsx CODE:

import {
  isMantineColorScheme,
  MantineColorScheme,
  MantineColorSchemeManager,
} from '@mantine/core';

export interface LocalStorageColorSchemeManagerOptions {
  /** Local storage key used to retrieve value with `localStorage.getItem(key)`, `mantine-color-scheme` by default */
  key?: string;
}

export function localStorageColorSchemeManager({
  key = 'mantine-color-scheme',
}: LocalStorageColorSchemeManagerOptions = {}): MantineColorSchemeManager {
  let handleStorageEvent: (event: StorageEvent) => void;

  return {
    get: (defaultValue) => {
      if (typeof window === 'undefined') {
        return defaultValue;
      }

      try {
        return (
          (window.localStorage.getItem(key) as MantineColorScheme) ||
          defaultValue
        );
      } catch {
        return defaultValue;
      }
    },

    set: (value) => {
      try {
        window.localStorage.setItem(key, value);
      } catch (error) {
        // eslint-disable-next-line no-console
        console.warn(
          '[@mantine/core] Local storage color scheme manager was unable to save color scheme.',
          error
        );
      }
    },

    subscribe: (onUpdate) => {
      handleStorageEvent = (event) => {
        if (
          event.storageArea === window.localStorage &&
          event.key === key
        ) {
          isMantineColorScheme(event.newValue) &&
            onUpdate(event.newValue);
        }
      };

      window.addEventListener('storage', handleStorageEvent);
    },

    unsubscribe: () => {
      window.removeEventListener('storage', handleStorageEvent);
    },

    clear: () => {
      window.localStorage.removeItem(key);
    },
  };
}

TITLE: Defining the useDebouncedValue Hook in React with TypeScript DESCRIPTION: This snippet defines the TypeScript function signature for the useDebouncedValue hook, which is intended for React applications requiring debounced value updates. It takes a value of any type T, a wait duration in milliseconds, and an optional options object supporting a boolean leading property. The hook returns a readonly tuple with the debounced value and a cancel function. Proper usage requires React, knowledge of hooks, and optionally TypeScript support for strong typing. The leading option enables immediate updates, while the cancel callback allows aborting pending debounced updates. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-debounced-value.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

function useDebouncedValue<T = any>(
  value: T,
  wait: number,
  options?: {
    leading: boolean;
  }
): readonly [T, () => void];

TITLE: Applying Responsive Styles with smaller-than and larger-than Mixins - SCSS DESCRIPTION: Shows usage of smaller-than and larger-than mixins to apply CSS styles based on screen size breakpoints. The mixins generate media queries with max-width or min-width in em units, carefully adjusting breakpoints to avoid overlap. The example covers both fixed pixel breakpoints and usage with Mantine breakpoint variables. This simplifies writing responsive CSS rules tied to viewport widths. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/postcss-preset.mdx#_snippet_3

LANGUAGE: SCSS CODE:

.demo {
  @mixin smaller-than 320px {
    color: red;
  }

  @mixin larger-than 320px {
    color: blue;
  }
}

LANGUAGE: SCSS CODE:

@media (max-width: 19.99375em) {
  .demo {
    color: red;
  }
}

@media (min-width: 20em) {
  .demo {
    color: blue;
  }
}

LANGUAGE: SCSS CODE:

.demo {
  @mixin smaller-than $mantine-breakpoint-sm {
    color: red;
  }

  @mixin larger-than $mantine-breakpoint-sm {
    color: blue;
  }
}

TITLE: Setting up ModalsProvider with MantineProvider in TypeScript DESCRIPTION: Initializes modal context by wrapping the application with MantineProvider and ModalsProvider components. This setup is required to enable modal functionalities from the @mantine/modals package in a React TypeScript application. No props are passed here, demonstrating basic usage. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/modals.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { MantineProvider } from '@mantine/core';
import { ModalsProvider } from '@mantine/modals';

function Demo() {
  return (
    <MantineProvider>
      <ModalsProvider>{/* Your app here */}</ModalsProvider>
    </MantineProvider>
  );
}

TITLE: Configure Mantine Breakpoints with MantineProvider (TSX) DESCRIPTION: Demonstrates how to override the default Mantine theme breakpoints using createTheme and MantineProvider. This allows customizing the viewport widths at which responsive styles apply. Breakpoints are defined in em units. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/responsive.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  breakpoints: {
    xs: '30em',
    sm: '48em',
    md: '64em',
    lg: '74em',
    xl: '90em',
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Customizing Mantine Headings Theme in TSX DESCRIPTION: This TypeScript React snippet demonstrates how to override default heading styles in Mantine by using the createTheme function and modifying the headings.sizes property. It shows how to set custom fontSize, lineHeight, and fontWeight for h1 and h2 headings. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_15

LANGUAGE: tsx CODE:

import { createTheme } from '@mantine/core';

const theme = createTheme({
  headings: {
    sizes: {
      h1: {
        fontSize: '2rem',
        lineHeight: '1.5',
        fontWeight: '500',
      },
      h2: {
        fontSize: '1.5rem',
        lineHeight: '1.6',
        fontWeight: '500',
      },
    },
    // ...
  },
});

TITLE: Customizing input props via InputFeatures DESCRIPTION: This code demonstrates how to pass additional input-related properties such as styles, placeholder, or event handlers through 'InputFeatures', enabling detailed customization of the input element within TagsInput. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tags-input.mdx#_snippet_20

LANGUAGE: TypeScript CODE:

<Demo data={TagsInputDemos.configurator} />

TITLE: Configuring PostCSS with mantine-preset DESCRIPTION: Creates a 'postcss.config.cjs' file with plugins for Mantine preset and simple variables, defining custom breakpoints for responsiveness. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/next.mdx#_snippet_4

LANGUAGE: JavaScript CODE:

module.exports = {
  plugins: {
    'postcss-preset-mantine': {},
    'postcss-simple-vars': {
      variables: {
        'mantine-breakpoint-xs': '36em',
        'mantine-breakpoint-sm': '48em',
        'mantine-breakpoint-md': '62em',
        'mantine-breakpoint-lg': '75em',
        'mantine-breakpoint-xl': '88em',
      },
    },
  },
};

TITLE: Configuring Next.js App with Mantine Emotion Providers DESCRIPTION: Wraps the main application component in _app.tsx with MantineEmotionProvider and MantineProvider. This sets up the necessary context for Mantine components and enables the use of Emotion's sx and styles props via emotionTransform. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_6

LANGUAGE: TSX CODE:

import '@mantine/core/styles.css';

import Head from 'next/head';
import { MantineProvider } from '@mantine/core';
import {
  emotionTransform,
  MantineEmotionProvider,
} from '@mantine/emotion';
import { emotionCache } from '../emotion/cache';

export default function App({ Component, pageProps }: any) {
  return (
    <MantineEmotionProvider cache={emotionCache}>
      <MantineProvider stylesTransform={emotionTransform}>
        <Head>
          <title>Mantine Template</title>
          <meta
            name="viewport"
            content="minimum-scale=1, initial-scale=1, width=device-width, user-scalable=no"
          />
          <link rel="shortcut icon" href="/favicon.svg" />
        </Head>
        <Component {...pageProps} />
      </MantineProvider>
    </MantineEmotionProvider>
  );
}

TITLE: Implementing a Controlled Radio Group in Mantine DESCRIPTION: Demonstrates how to create a controlled Radio.Group component with multiple Radio options. The group's value is managed with React state and includes a label, description, and required indicator. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/radio.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Radio } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('react');

  return (
    <Radio.Group
      value={value}
      onChange={setValue}
      name="favoriteFramework"
      label="Select your favorite framework/library"
      description="This is anonymous"
      withAsterisk
    >
      <Radio value="react" label="React" />
      <Radio value="svelte" label="Svelte" />
      <Radio value="ng" label="Angular" />
      <Radio value="vue" label="Vue" />
    </Radio.Group>
  );
}

TITLE: Configuring postcss-preset-mantine Plugin in PostCSS - JavaScript DESCRIPTION: Shows how to set up postcss-preset-mantine in the PostCSS configuration file postcss.config.cjs, enabling the preset's plugins with default options or custom features such as autoRem and custom mixins. Dependencies include PostCSS and the preset package. The input is a module export for plugins, and the output is the activated preset modifying CSS processing behavior according to configuration. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/postcss-preset.mdx#_snippet_0

LANGUAGE: JavaScript CODE:

module.exports = {
  plugins: {
    'postcss-preset-mantine': {},
  },
};

LANGUAGE: JavaScript CODE:

module.exports = {
  plugins: {
    'postcss-preset-mantine': {
      autoRem: true,
    },
  },
};

LANGUAGE: TypeScript CODE:

module.exports = {
  plugins: {
    'postcss-preset-mantine': {
      autoRem: true,
      mixins: {
        clearfix: {
          '&::after': {
            content: '""',
            display: 'table',
            clear: 'both',
          },
        },
        circle: (_mixin, size) => ({
          borderRadius: '50%',
          width: size,
          height: size,
        }),
      },
    },
    // ... Other plugins
  },
};

LANGUAGE: TypeScript CODE:

module.exports = {
  'postcss-preset-mantine': {
    features: {
      lightDarkFunction: false,
      nested: false,
      colorMixAlpha: false,
      remEmFunctions: false,
      mixins: false,
    },
  },
};

TITLE: Using the useIsomorphicEffect Hook in React with Mantine DESCRIPTION: This example demonstrates how to import and use the useIsomorphicEffect hook from the Mantine hooks library. The hook functions as a replacement for useLayoutEffect, allowing developers to perform layout effects in both browser and server environments by setting the document title. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-isomorphic-effect.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useIsomorphicEffect } from '@mantine/hooks';

function Demo() {
  useIsomorphicEffect(() => {
    document.title = 'title';
  });

  return null;
}

TITLE: Styling nested elements with Mantine styles prop DESCRIPTION: Shows how to customize deeply nested elements within Mantine components using the styles prop to target specific component parts. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/dynamic-css-styles.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { Button } from '@mantine/core';

interface DemoProps {
  color: string;
}

function Demo({ color }: DemoProps) {
  return (
    <Button styles={{ label: { backgroundColor: color } }}>
      My demo
    </Button>
  );
}

TITLE: Style array to merge Mantine styles DESCRIPTION: Explains how to use an array of style objects and/or functions to merge multiple styles into a single style object for a Mantine Box component. Requires the @mantine/core package. This approach is useful for creating wrappers around Mantine components while preserving the ability to override styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/style.mdx#_snippet_3

LANGUAGE: typescript CODE:

import { Box, MantineStyleProp } from '@mantine/core';

interface DemoProps {
  style?: MantineStyleProp;
}

function Demo({ style }: DemoProps) {
  return <Box style={[{ color: 'red' }, style]} />;
}

TITLE: Adding Default Styles to Mantine Components in Theme - TSX DESCRIPTION: Illustrates how to define default styles for a Mantine component like Text within the components section of a custom theme created with createTheme. It shows using the styles function signature with theme and utilities (u) to apply color scheme specific styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_14

LANGUAGE: TSX CODE:

import { createTheme, MantineTheme, TextProps } from '@mantine/core';
import { EmotionHelpers } from '@mantine/emotion';

export const theme = createTheme({
  components: {
    Text: {
      styles: (
        theme: MantineTheme,
        _props: TextProps,
        u: EmotionHelpers
      ) => ({
        root: {
          [u.light]: {
            color: theme.colors.blue[7],
          },
        },
      }),
    },
  },
});

TITLE: Configuring enhanceGetInputProps for Input Disabling DESCRIPTION: This code demonstrates using enhanceGetInputProps within a @mantine/form hook. It disables a TextInput component based on the field path. Dependencies include @mantine/core and @mantine/form. The input is disabled when the field path matches 'name'. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_9

LANGUAGE: tsx CODE:

import { NumberInput, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';

interface FormValues {
  name: string;
  age: number | string;
}

function Demo() {
  const form = useForm<FormValues>({
    initialValues: { name: '', age: '' },
    enhanceGetInputProps: (payload) => ({
      disabled: payload.field === 'name',
    }),
  });

  return (
    <>
      <TextInput {...form.getInputProps('name')} label="Name" placeholder="Name" />
      <NumberInput {...form.getInputProps('age')} label="Age" placeholder="Age" mt="md" />
    </>
  );
}


TITLE: ActionIcon Accessibility Demo DESCRIPTION: This example illustrates how to make ActionIcon accessible using either the aria-label attribute or the VisuallyHidden component. It showcases two ways to provide descriptive labels for screen readers, enhancing accessibility. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/action-icon.mdx#_snippet_3

LANGUAGE: TypeScript CODE:

import { IconHeart } from '@tabler/icons-react';
import { ActionIcon, VisuallyHidden } from '@mantine/core';

function Demo() {
  return (
    <>
      <ActionIcon aria-label="Like post">
        <IconHeart />
      </ActionIcon>

      <ActionIcon>
        <VisuallyHidden>Like post</VisuallyHidden>
        <IconHeart />
      </ActionIcon>
    </>
  );
}

TITLE: Managing a Controlled Mantine Switch.Group in TSX DESCRIPTION: Illustrates how to manage the state of multiple Switch components grouped within a Switch.Group. The useState hook manages an array of selected string values, which is bound to the value prop of Switch.Group. The onChange prop updates the state array when any switch within the group changes. Requires react and @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/switch.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Switch } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState<string[]>([]);

  return (
    <Switch.Group value={value} onChange={setValue}>
      <Switch value="react" label="React" />
      <Switch value="svelte" label="Svelte" />
    </Switch.Group>
  );
}

TITLE: Using renderRoot with react-router-dom NavLink (TSX) DESCRIPTION: Provides an example of using the renderRoot prop on a Mantine Button component to render it as a react-router-dom NavLink. This is useful when the target component's props (like className expecting a function) are incompatible with the standard component prop, allowing custom prop handling within the render callback. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.1.0.md#_snippet_3

LANGUAGE: tsx CODE:

import cx from 'clsx';
import { Button } from '@mantine/core';
import { NavLink } from 'react-router-dom';

function Demo() {
  return (
    <Button
      renderRoot={({ className, ...others }) => (
        <NavLink
          className={({ isActive }) => cx(className, { 'active-class': isActive })}
          {...others}
        />
      )}
    >
      React router NavLink
    </Button>
  );
}

TITLE: Applying Responsive Style Props with Object Syntax (TypeScript TSX) DESCRIPTION: Shows how to use Mantine style props with an object format to enable responsive breakpoints directly in component props. In this example, the 'w' prop (for width) is supplied as an object with values for 'base', 'sm', and 'lg' breakpoints. Requires @mantine/core and assumes theme.breakpoints configuration. Each breakpoint value overrides the previous as the viewport grows. This method is more computationally expensive and is not recommended for large lists. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/style-props.mdx#_snippet_3

LANGUAGE: TSX CODE:

import { Box } from '@mantine/core';

function Demo() {
  return <Box w={{ base: 320, sm: 480, lg: 640 }} />;
}

TITLE: Enabling Sticky Table Headers with Mantine Table (TypeScript/React) DESCRIPTION: Shows how to enable sticky table headers using the stickyHeader and stickyHeaderOffset props in Mantine Table. The elements array serves as data, and the table header will remain visible while scrolling if the page is long enough. Output is a Table with a sticky Thead section and custom rows built from data. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.2.0.md#_snippet_5

LANGUAGE: TypeScript CODE:

import { Table } from '@mantine/core';

const elements = [
  { position: 6, mass: 12.011, symbol: 'C', name: 'Carbon' },
  { position: 7, mass: 14.007, symbol: 'N', name: 'Nitrogen' },
  { position: 39, mass: 88.906, symbol: 'Y', name: 'Yttrium' },
  { position: 56, mass: 137.33, symbol: 'Ba', name: 'Barium' },
  { position: 58, mass: 140.12, symbol: 'Ce', name: 'Cerium' },
];

function Demo() {
  const rows = elements.map((element) => (
    <Table.Tr key={element.name}>
      <Table.Td>{element.position}</Table.Td>
      <Table.Td>{element.name}</Table.Td>
      <Table.Td>{element.symbol}</Table.Td>
      <Table.Td>{element.mass}</Table.Td>
    </Table.Tr>
  ));

  return (
    <Table stickyHeader stickyHeaderOffset={60}>
      <Table.Thead>
        <Table.Tr>
          <Table.Th>Element position</Table.Th>
          <Table.Th>Element name</Table.Th>
          <Table.Th>Symbol</Table.Th>
          <Table.Th>Atomic mass</Table.Th>
        </Table.Tr>
      </Table.Thead>
      <Table.Tbody>{rows}</Table.Tbody>
      <Table.Caption>Scroll page to see sticky thead</Table.Caption>
    </Table>
  );
}

TITLE: Importing Mantine Core Styles (v7) DESCRIPTION: Demonstrates the new method for importing core Mantine styles in v7 after the migration to native CSS. This replaces the previous Emotion-based styling approach. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_0

LANGUAGE: tsx CODE:

import '@mantine/core/styles.css';

TITLE: Handling Server Side Rendering with useMediaQuery Hook in Mantine DESCRIPTION: Shows how to configure useMediaQuery to provide an initial value during server-side rendering, bypassing the absence of window.matchMedia API. Specifies setting getInitialValueInEffect to false to disable initial value computation in effects. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-media-query.mdx#_snippet_2

LANGUAGE: TypeScript CODE:

import { useMediaQuery } from '@mantine/hooks';

function Demo() {
  // Set initial value in second argument and getInitialValueInEffect option to false
  const matches = useMediaQuery('(max-width: 40em)', true, {
    getInitialValueInEffect: false,
  });
}

TITLE: Merging Custom Font Sizes with Default Mantine Theme (TypeScript) DESCRIPTION: This example shows how theme.fontSizes merges with DEFAULT_THEME.fontSizes, allowing you to define only specific font sizes while inheriting others from the default theme. This approach simplifies customization by only requiring changes for desired values. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_7

LANGUAGE: tsx CODE:

import { createTheme } from '@mantine/core';

// Changes only xs font size,
// other values will be taken from the DEFAULT_THEME
const theme = createTheme({
  fontSizes: {
    xs: '0.5rem',
  },
});

TITLE: Color Manipulation Using alpha, lighten, and darken Functions - SCSS DESCRIPTION: Demonstrates advanced CSS color manipulation with alpha, lighten, and darken functions that leverage the CSS color-mix feature. The alpha function adds transparency to colors, while lighten and darken mix in white or black colors respectively. The example shows input using these functions and their output transforming to compatible color-mix syntax with proper color percentages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/postcss-preset.mdx#_snippet_4

LANGUAGE: SCSS CODE:

.demo {
  color: alpha(var(--mantine-color-red-4), 0.5);
  border: 1px solid alpha(#ffc, 0.2);
}

LANGUAGE: SCSS CODE:

.demo {
  color: color-mix(
    in srgb,
    var(--mantine-color-red-4),
    transparent 50%
  );
  border: 1px solid color-mix(in srgb, #ffc, transparent 80%);
}

LANGUAGE: SCSS CODE:

.demo {
  color: lighten(var(--mantine-color-red-4), 0.5);
  border: 1px solid darken(#ffc, 0.2);
}

LANGUAGE: SCSS CODE:

.demo {
  color: color-mix(in srgb, var(--mantine-color-red-4), white 50%);
  border: 1px solid color-mix(in srgb, #ffc, black 20%);
}

TITLE: Configuring Shared Labels for Confirm Modals with ModalsProvider in TypeScript DESCRIPTION: Sets up the ModalsProvider with custom default labels for confirm and cancel buttons in confirmation modals. This provides consistency across confirmation dialogs by defining shared button text. Dependencies include the @mantine/modals package and React with TypeScript. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/modals.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { ModalsProvider } from '@mantine/modals';

function Demo() {
  return (
    <ModalsProvider labels={{ confirm: 'Submit', cancel: 'Cancel' }}>
      {/* Your app here */}
    </ModalsProvider>
  );
}

TITLE: Custom valueFormatter function usage with DatePickerInput in TypeScript DESCRIPTION: Shows usage of the 'valueFormatter' prop in '@mantine/dates' DatePickerInput component to provide a custom display format for selected dates. The formatter function handles different selection types, specifically 'multiple' type with an array of dates, formatting them using dayjs with locale and format parameters. A controlled component example demonstrates updating and using state with 'useState'. Requires 'dayjs' as a dependency for date manipulation. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.5.0.md#_snippet_2

LANGUAGE: tsx CODE:

import dayjs from 'dayjs';
import { useState } from 'react';
import { DateFormatter, DatePickerInput } from '@mantine/dates';

const formatter: DateFormatter = ({ type, date, locale, format }) => {
  if (type === 'multiple' && Array.isArray(date)) {
    if (date.length === 1) {
      return dayjs(date[0]).locale(locale).format(format);
    }

    if (date.length > 1) {
      return `${date.length} dates selected`;
    }

    return '';
  }

  return '';
};

function Demo() {
  const [value, setValue] = useState<Date[]>([]);

  return (
    <DatePickerInput
      label="Pick 2 dates or more"
      placeholder="Pick 2 dates or more"
      value={value}
      onChange={setValue}
      type="multiple"
      valueFormatter={formatter}
    />
  );
}

TITLE: Importing Mantine Component Props Types (TypeScript) DESCRIPTION: Demonstrates how to import the TypeScript prop types for Mantine components like Button and DatePicker using the type keyword. This allows for type checking when using component props. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_0

LANGUAGE: tsx CODE:

import type { ButtonProps } from '@mantine/core';
import type { DatePickerProps } from '@mantine/dates';

TITLE: Setting up a named form with useForm DESCRIPTION: Shows how to create a form with the useForm hook and assign it a name that can be referenced by form actions. The name property is essential for connecting form actions to a specific form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/actions.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

export interface DemoFormValues {
  name: string;
  age: number;
}

function Demo() {
  const form = useForm<DemoFormValues>({
    mode: 'uncontrolled',
    name: 'demo-form',
    initialValues: {
      name: '',
      age: 0,
    },
  });
}

TITLE: Using form.getValues to Access Current Form Values in Mantine DESCRIPTION: Example demonstrating how to use form.getValues() to access current form values in both controlled and uncontrolled modes, showing why it's preferred over form.values. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/uncontrolled.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { name: 'John Doe' },
});

form.getValues(); // { name: 'John Doe' }

form.setValues({ name: 'John Smith' });
form.getValues(); // { name: 'John Smith' }

TITLE: Explaining Polymorphic Components in Mantine DESCRIPTION: This snippet provides a conceptual explanation of polymorphic components, describing their ability to change the root element via the 'component' prop, with examples showcasing default behavior and customizations. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/polymorphic-in-polymorphic.mdx#_snippet_1

LANGUAGE: TypeScript CODE:

## What is polymorphic component?

A polymorphic component is a component which root element can be changed with component prop.
All polymorphic components have a default element which is used when component prop is not provided.
For example, the `Button` component default element is `button` and it can be changed to
`a` or any other element or component:

```tsx
import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button component="a" href="https://mantine.dev/" target="_blank">
      Mantine website
    </Button>
  );
}

----------------------------------------

TITLE: Updating Form State Externally Using Form Actions in Mantine (TypeScript/React)
DESCRIPTION: Illustrates updating a Mantine form's state from an external component via form actions after fetching data asynchronously. Depends on '@mantine/core', '@mantine/form', and React's useEffect. React's Button component allows the user to reset the form by invoking demoFormActions.reset(). The demoFormActions must be imported and corresponds to a form named 'demo-form'.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.2.0.md#_snippet_3

LANGUAGE: TypeScript
CODE:

import { useEffect } from 'react'; import { Button } from '@mantine/core'; import { demoFormActions } from './demoFormActions';

function ExternalComponent() { useEffect(() => { fetch('/api/user') .then((res) => res.json()) .then((res) => demoFormActions.setValues({ name: res.name, age: res.age, }) ); }, []);

return <Button onClick={() => demoFormActions.reset()}>Reset demo form</Button>; }


----------------------------------------

TITLE: React Controlled JsonInput Component Example in TypeScript
DESCRIPTION: This code demonstrates a controlled React component utilizing the JsonInput component, managing its input value via useState. It highlights how to create a controlled form input, capturing user input, and updating the component state accordingly.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/json-input.mdx#_snippet_2

LANGUAGE: TypeScript
CODE:

import { useState } from 'react'; import { JsonInput } from '@mantine/core';

function Demo() { const [value, setValue] = useState(''); return <JsonInput value={value} onChange={setValue} />; }


----------------------------------------

TITLE: Converting Space-separated px Values to rem (Mantine rem Function, TypeScript)
DESCRIPTION: Demonstrates the use of Mantine's rem utility function to convert space-separated px values to rem units, supporting responsive and scalable sizing. Requires '@mantine/core' v1.11.0+ for rem function enhancements. Input: px strings, Output: CSS calc() strings.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.3.0.md#_snippet_5

LANGUAGE: tsx
CODE:

import { rem } from '@mantine/core';

rem('16px 32px'); // -> calc(1rem * var(--mantine-scale)) calc(2rem * var(--mantine-scale))


----------------------------------------

TITLE: Theme Color Customization
DESCRIPTION: Demonstrates how to customize the default dark color scheme in Mantine by overriding the `theme.colors.dark` values in the `MantineProvider`. It provides the old color values and the code to apply them.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-3-0.mdx#_snippet_5

LANGUAGE: tsx
CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({ colors: { dark: [ '#C1C2C5', '#A6A7AB', '#909296', '#5c5f66', '#373A40', '#2C2E33', '#25262b', '#1A1B1E', '#141517', '#101113', ], }, });

function Demo() { return ( <MantineProvider theme={theme}> {/* Your app here */} </MantineProvider> ); }


LANGUAGE: scss
CODE:

--mantine-color-dark-0: #c9c9c9; --mantine-color-dark-1: #b8b8b8; --mantine-color-dark-2: #828282; --mantine-color-dark-3: #696969; --mantine-color-dark-4: #424242; --mantine-color-dark-5: #3b3b3b; --mantine-color-dark-6: #2e2e2e; --mantine-color-dark-7: #242424; --mantine-color-dark-8: #1f1f1f; --mantine-color-dark-9: #141414;


----------------------------------------

TITLE: Setting nested object values with Mantine useForm hook in TypeScript
DESCRIPTION: Shows how to update nested object fields individually or set the entire nested object at once within a form initialized with useForm. Utilizes the setFieldValue method accepting dot-notated string property paths. The code requires '@mantine/form' and expects an initial form state with a user object containing name and occupation fields. Inputs are new field values either for individual keys or a complete nested object, and outputs are updated form state values.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/nested.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', initialValues: { user: { name: '', occupation: '', }, }, });

// You can set values for each field individually form.setFieldValue('user.name', 'John'); form.setFieldValue('user.occupation', 'Engineer');

// Or set the entire object form.setFieldValue('user', { name: 'Jane', occupation: 'Architect' });


----------------------------------------

TITLE: Customizing onSubmit Prevent Default Behavior - Mantine (TypeScript/TSX)
DESCRIPTION: This snippet demonstrates configuring the onSubmitPreventDefault parameter of useForm to alter whether form submissions automatically call event.preventDefault(). You can specify 'always' (default), 'never', or 'validation-failed' as the value depending on desired stopping of native form submission. Prerequisite is initialization of useForm with the desired mode and option.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/use-form.mdx#_snippet_6

LANGUAGE: TSX
CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled', onSubmitPreventDefault: 'never', });


----------------------------------------

TITLE: Creating accessible Tooltips with keyboard focus support
DESCRIPTION: Shows how to make tooltips accessible to screen readers and keyboard users by enabling focus events, following WAI-ARIA recommendations for proper semantic structure.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tooltip.mdx#_snippet_5

LANGUAGE: tsx
CODE:

import { Button, Tooltip } from '@mantine/core';

// Tooltip will be visible for screen readers function Demo() { return ( <Tooltip label="Tooltip" events={{ hover: true, focus: true, touch: false }} > <Button>Button with tooltip</Button> </Tooltip> ); }


----------------------------------------

TITLE: Defining Custom Shadows in Mantine Theme (TSX)
DESCRIPTION: This TypeScript/React snippet demonstrates how to define custom shadow values for Mantine components. By configuring the `shadows` property within `createTheme`, you can specify distinct box-shadow styles for different sizes (xs, sm, md, lg, xl), which are then exposed as `--mantine-shadow-*` CSS variables.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_24

LANGUAGE: tsx
CODE:

import { createTheme } from '@mantine/core';

const theme = createTheme({ shadows: { xs: '0 1px 2px rgba(0, 0, 0, 0.1)', sm: '0 1px 3px rgba(0, 0, 0, 0.1)', md: '0 2px 4px rgba(0, 0, 0, 0.1)', lg: '0 4px 8px rgba(0, 0, 0, 0.1)', xl: '0 8px 16px rgba(0, 0, 0, 0.1)', }, });


----------------------------------------

TITLE: Using rem/em Utilities in Vanilla Extract Styles (TypeScript)
DESCRIPTION: Shows how to use the `rem` and `em` utility functions from `@mantine/core` within Vanilla Extract style definitions. This allows converting pixel values to relative units, useful for accessibility and responsive design, including within media queries.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/vanilla-extract.mdx#_snippet_3

LANGUAGE: tsx
CODE:

// Demo.css.ts import { style } from '@vanilla-extract/css'; import { rem } from '@mantine/core';

export const demo = style({ fontSize: rem(16),

'@media': { [(min-width: ${em(768)})]: { fontSize: rem(18), }, }, });


----------------------------------------

TITLE: Setting up Next.js Document for Mantine Emotion SSR
DESCRIPTION: Configures the Next.js `_document.tsx` file to handle server-side rendering of Emotion styles. It imports the Emotion cache, creates an Emotion server instance, and uses `createGetInitialProps` from `@mantine/emotion` to inject server-rendered styles into the HTML.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_5

LANGUAGE: TSX
CODE:

import NextDocument, { Head, Html, Main, NextScript, } from 'next/document'; import createEmotionServer from '@emotion/server/create-instance'; import { ColorSchemeScript } from '@mantine/core'; import { createGetInitialProps } from '@mantine/emotion'; // Import cache created in the previous step import { emotionCache } from '../emotion/cache';

export default function Document() { return ( <Html lang="en"> <Head> <ColorSchemeScript /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); }

const stylesServer = createEmotionServer(emotionCache);

Document.getInitialProps = createGetInitialProps( NextDocument, stylesServer );


----------------------------------------

TITLE: Generating Nonce Attribute for Style Tags in MantineProvider (TypeScript)
DESCRIPTION: Shows how to supply a function to generate a nonce value for `<style>` tags for security purposes, supporting Content Security Policy (CSP) compliance.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/mantine-provider.mdx#_snippet_10

LANGUAGE: TypeScript
CODE:

import { MantineProvider } from '@mantine/core';

// Example function implementation for nonce const getStyleNonce = () => { return 'random-generated-nonce'; };

function Demo() { return ( <MantineProvider getStyleNonce={getStyleNonce}> {/* Your app here */} </MantineProvider> ); }


----------------------------------------

TITLE: Defining Hover Styles with hover Mixin - CSS
DESCRIPTION: Illustrates how to create hover styles using the `hover` mixin, which handles hover and active states across different devices and interaction modes. The mixin generates media queries for devices that support hover and those that do not, applying appropriate pseudo-classes for each scenario to ensure consistent user experience.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/postcss-preset.mdx#_snippet_5

LANGUAGE: CSS
CODE:

.demo { @mixin hover { color: orange; } }


LANGUAGE: CSS
CODE:

@media (hover: hover) { .demo:hover { color: orange; } }

@media (hover: none) { .demo:active { color: orange; } }


----------------------------------------

TITLE: Creating a Shared Theme Object in src/theme.ts for Mantine and Storybook
DESCRIPTION: The snippet demonstrates defining a theme object using Mantine's createTheme function. This shared theme allows consistent styling across the application and Storybook environment by importing and using the same theme in MantineProvider components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/storybook.mdx#_snippet_3

LANGUAGE: TypeScript
CODE:

// src/theme.ts import { createTheme } from '@mantine/core';

export const theme = createTheme({ fontFamily: 'serif', // ... other theme override properties });


----------------------------------------

TITLE: Setting Color Transparency with alpha in Mantine Core (TSX)
DESCRIPTION: Shows how to use the `alpha` function from `@mantine/core` to apply transparency to a color. It takes a color string and an alpha value (0-1) as arguments. Returns the color in rgba format if possible, otherwise uses `color-mix` with `transparent` for CSS variables, noting potential browser compatibility issues.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/color-functions.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { alpha } from '@mantine/core';

alpha('#4578FC', 0.45); // -> rgba(69, 120, 252, 0.45) alpha('var(--mantine-color-gray-4)', 0.74); // -> color-mix(in srgb, var(--mantine-color-gray-4), transparent 26%)


----------------------------------------

TITLE: Controlled Checkbox.Group Example (React)
DESCRIPTION: This example showcases a controlled Checkbox.Group component using the `useState` hook to manage an array of string values representing the selected checkboxes.  The `onChange` event updates the selected values, enabling external control of the group's state.  It imports `useState` from `react` and `Checkbox` from `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/checkbox.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { Checkbox } from '@mantine/core';

function Demo() { const [value, setValue] = useState<string[]>([]);

return ( <Checkbox.Group value={value} onChange={setValue}> <Checkbox value="react" label="React" /> <Checkbox value="svelte" label="Svelte" /> </Checkbox.Group> ); }


----------------------------------------

TITLE: Demonstrating Mantine sx Prop with Object and Function Syntax (React/TypeScript)
DESCRIPTION: A React component illustrating two common ways to use the `sx` prop on Mantine components: providing a direct style object and providing a function that receives the theme and utility functions (`u`). The function syntax is useful for applying theme-dependent or responsive styles. Examples are shown on `Box` and `Button` components. Requires `@mantine/core`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_12

LANGUAGE: tsx
CODE:

import { Box, Button } from '@mantine/core';

function Demo() { return ( <> <Box sx={{ padding: 40, '&:hover': { padding: 80 }, }} > Box with object sx </Box>

  <Button
    sx={(theme, u) => ({
      padding: 10,

      [u.light]: {
        backgroundColor: theme.colors.blue[0],
        color: theme.colors.blue[9],
        '&:hover': {
          backgroundColor: theme.colors.blue[1],
        },
      },

      [u.dark]: {
        backgroundColor: theme.colors.blue[9],
        color: theme.colors.blue[0],
        '&:hover': {
          backgroundColor: theme.colors.blue[8],
        },
      },
    })}
  >
    Button with function sx
  </Button>
</>

); }


----------------------------------------

TITLE: Using Mantine colorsTuple Function in createTheme
DESCRIPTION: Illustrates the usage of the new colorsTuple helper function within Mantine's createTheme. It shows how to generate a 10-value color tuple from a single color string or from a dynamically generated array of 10 color strings for theme customization.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.7.0.md#_snippet_3

LANGUAGE: tsx
CODE:

import { colorsTuple, createTheme } from '@mantine/core';

const theme = createTheme({ colors: { custom: colorsTuple('#FFC0CB'), dynamic: colorsTuple(Array.from({ length: 10 }, (_, index) => '#FFC0CB')), }, });


----------------------------------------

TITLE: Disabled State Example for Fieldset Component
DESCRIPTION: Demonstrates how to disable all inputs and buttons inside the fieldset component by setting the disabled prop in demo data. This illustrates the component's ability to handle disabled states for accessibility and control purposes.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/fieldset.mdx#_snippet_3

LANGUAGE: JavaScript
CODE:
<Demo data={FieldsetDemos.disabled} /> ```

TITLE: Configuring onSubmitPreventDefault in use-form DESCRIPTION: This snippet shows how to customize default form submission behavior in 'useForm' by setting 'onSubmitPreventDefault' option to control whether 'event.preventDefault()' is called during form submission, enabling server integration or default behavior. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-15-0.mdx#_snippet_7

LANGUAGE: TypeScript CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  onSubmitPreventDefault: 'never',
});

TITLE: Storing Theme Override in a Variable DESCRIPTION: Shows how to create a theme override object using the createTheme function and store it in a variable before passing it to the MantineProvider component. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/theme-object.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const myTheme = createTheme({
  primaryColor: 'orange',
  defaultRadius: 0,
});

function Demo() {
  return (
    <MantineProvider theme={myTheme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Using the use-matches Hook for Responsive Styles in React DESCRIPTION: Shows how to use the new use-matches hook from @mantine/core to apply responsive styles based on multiple breakpoints, providing an alternative to use-media-query. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.9.0.md#_snippet_5

LANGUAGE: tsx CODE:

import { Box, useMatches } from '@mantine/core';

function Demo() {
  const color = useMatches({
    base: 'blue.9',
    sm: 'orange.9',
    lg: 'red.9',
  });

  return (
    <Box bg={color} c="white" p="xl">
      Box with color that changes based on screen size
    </Box>
  );
}

TITLE: Applying Styles to Disabled Button in CSS DESCRIPTION: This CSS snippet shows how to style the disabled button using the data-disabled attribute. It sets the text color to gray when the button is disabled. The &[data-disabled] selector is used to specifically target the disabled state. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/data-attributes.mdx#_snippet_2

LANGUAGE: css CODE:

.my-button {
  color: var(--mantine-color-black);

  &[data-disabled] {
    color: var(--mantine-color-gray-5);
  }
}


TITLE: Configuring Valibot Resolver for Nested Validation DESCRIPTION: This code demonstrates Valibot validation on nested form fields. It defines a schema with a nested object and applies it to a @mantine/form instance. Dependencies are the same as the previous example, including @mantine/form, valibot, and mantine-form-valibot-resolver. The validate method is called, and errors are accessed through form.errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_15

LANGUAGE: tsx CODE:

import { valibotResolver } from 'mantine-form-valibot-resolver';
import { minLength, object, string } from 'valibot';
import { useForm } from '@mantine/form';

const nestedSchema = object({
  nested: object({
    field: string([minLength(2, 'Field should have at least 2 letters')]),
  }),
});

const form = useForm({
  initialValues: {
    nested: {
      field: '',
    },
  },
  validate: valibotResolver(nestedSchema),
});

form.validate();
form.errors;
// -> {
//  'nested.field': 'Field should have at least 2 letters',
// }


TITLE: Using ColorSchemeScript with Props (TSX) DESCRIPTION: Demonstrates how to include additional HTML attributes like nonce and set the initial defaultColorScheme on the ColorSchemeScript component to customize its behavior. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/color-schemes.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { ColorSchemeScript } from '@mantine/core';

function Demo() {
  return (
    <ColorSchemeScript
      nonce="8IBTHwOdqNKAWeKl7plt8g=="
      defaultColorScheme="dark"
    />
  );
}

TITLE: Setting a Single Field Error with setFieldError – Mantine DESCRIPTION: Demonstrates using form.setFieldError to set an error for a specific field. This is useful for updating error states individually, driven by asynchronous validations or other dynamic conditions. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/errors.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { name: '', email: '' },
});

form.setFieldError('email', 'Invalid email');

form.errors; // -> { email: 'Invalid email' }


TITLE: Demonstrating UnstyledButton Polymorphic Capabilities DESCRIPTION: Renders a Polymorphic component to showcase how UnstyledButton can change between different HTML elements (button to anchor). SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/unstyled-button.mdx#_snippet_3

LANGUAGE: JSX CODE:

<Polymorphic
  defaultElement="button"
  changeToElement="a"
  component="UnstyledButton"
/>

TITLE: Sponsoring Mantine Development with Button Component (React/TSX) DESCRIPTION: This snippet demonstrates how to use the Mantine Button component to create a sponsor link. It includes an IconHeartFilled from @tabler/icons-react as a right section, custom sizing, minimum width, and alignment. The button acts as a link to OpenCollective. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/8-0-0.mdx#_snippet_0

LANGUAGE: tsx CODE:

<Button
  rightSection={<IconHeartFilled size={22} color="var(--mantine-color-red-7)" />}
  size="lg"
  miw={300}
  justify="space-between"
  children="Sponsor Mantine"
  variant="default"
  radius="md"
  component="a"
  href="https://opencollective.com/mantinedev"
/>

TITLE: Getting Form Values Type with TypeScript DESCRIPTION: Shows how to get the inferred form values type in TypeScript. This is useful for type checking in handleSubmit function or anywhere else in the code. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/values.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({ initialValues: { name: '', age: 0 } });

  // Get inferred form values type, will be `{ name: string; age: number }`
  type FormValues = typeof form.values;

  // Use values type in handleSubmit function or anywhere else
  const handleSubmit = (values: FormValues) => console.log(values);
}

TITLE: Using useValidatedState Mantine Hook TSX DESCRIPTION: Demonstrates the basic usage of the useValidatedState hook. It initializes the state with a value and a validation rule, then shows how updating the state affects the returned object's value, lastValidValue, and valid properties. Requires @mantine/hooks. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-validated-state.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useValidatedState } from '@mantine/hooks';

const [{ lastValidValue, value, valid }, setValue] =
  useValidatedState('valid', (state) => state === 'valid');

lastValidValue; // -> valid
value; // -> valid
valid; // -> true

setValue('invalid');

lastValidValue; // -> valid
value; // -> invalid
valid; // -> false

TITLE: Configuring Mantine ColorPicker Accessibility Labels (TSX) DESCRIPTION: This snippet demonstrates how to make the Mantine ColorPicker component accessible for screen readers. It shows how to set the saturationLabel, hueLabel, and alphaLabel props, which provide descriptive text for the respective sliders. The component is imported from @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/color-picker.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { ColorPicker } from '@mantine/core';

function Demo() {
  return (
    <ColorPicker
      saturationLabel="Saturation"
      hueLabel="Hue"
      alphaLabel="Alpha"
    />
  );
}

TITLE: Adding ColorSchemeScript for Server-Side Rendering (TSX) DESCRIPTION: Explains how to include ColorSchemeScript in the <head /> of the HTML document for applications with server-side rendering (SSR). This script helps manage color schemes correctly during the initial render on the server. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/getting-started.mdx#_snippet_3

LANGUAGE: TypeScript CODE:

import { ColorSchemeScript } from '@mantine/core';

function Demo() {
  return (
    <html lang="en">
      <head>
        <meta charSet="UTF-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1.0"
        />
        <title>My awesome app</title>

        <ColorSchemeScript />
      </head>
      <body>{/* Your app here */}</body>
    </html>
  );
}

TITLE: Using useToggle with Default Boolean State in TSX DESCRIPTION: Shows the default behavior of useToggle when called without arguments. It manages a boolean state, starting with false, and toggle() flips the state between false and true. Requires installation of @mantine/hooks. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-toggle.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useToggle } from '@mantine/hooks';

const [value, toggle] = useToggle();
// -> value === false
toggle(); // -> value === true

TITLE: Typing Functions with MantineColorScheme (TypeScript) DESCRIPTION: Shows how to use the MantineColorScheme union type to type function arguments that represent the color scheme. The example demonstrates a function that computes the actual color scheme based on the input and uses the useMantineColorScheme hook. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_6

LANGUAGE: tsx CODE:

import {
  MantineColorScheme,
  useMantineColorScheme,
} from '@mantine/core';

function getComputedColorScheme(colorScheme: MantineColorScheme) {
  return colorScheme === 'auto' ? 'light' : colorScheme;
}

function Demo() {
  const { colorScheme } = useMantineColorScheme();
  const computed = getComputedColorScheme(colorScheme);
}

TITLE: Creating a Controlled Radio Component in React with Mantine DESCRIPTION: Demonstrates how to implement a controlled Radio component using React state hooks. The component's checked state is managed by the useState hook and updated through the onChange event handler. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/radio.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Radio } from '@mantine/core';

function Demo() {
  const [checked, setChecked] = useState(false);
  return (
    <Radio
      checked={checked}
      onChange={(event) => setChecked(event.currentTarget.checked)}
    />
  );
}

TITLE: Controlled TimeInput Component (TSX) DESCRIPTION: Demonstrates how to manage the value of the TimeInput component using React's useState hook to create a controlled input. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/time-input.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { TimeInput } from '@mantine/dates';

function Demo() {
  const [value, setValue] = useState('');
  return (
    <TimeInput
      value={value}
      onChange={(event) => setValue(event.currentTarget.value)}
    />
  );
}

TITLE: Reading local storage value on initial render without hydration mismatch in TypeScript DESCRIPTION: This example illustrates how to configure the useLocalStorage hook to retrieve local storage data during the initial render by setting 'getInitialValueInEffect' to false. This is suitable for client-only applications or when output markup does not depend on local storage value. The hook initializes from local storage immediately, with 'dark' as fallback default. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/local-storage-effect.mdx#_snippet_1

LANGUAGE: TypeScript CODE:

import { useLocalStorage } from '@mantine/hooks';

function Demo() {
  const [value, setValue] = useLocalStorage<'light' | 'dark'>({
    key: 'color-scheme',
    defaultValue: 'dark',
    getInitialValueInEffect: false,
  });

  return <div>{value}</div>;
}

TITLE: Correct usage of extend() with 'use client' directive DESCRIPTION: This snippet demonstrates proper usage of the extend() function in Mantine with the addition of 'use client' at the top to enable client-side component extension. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/server-components.mdx#_snippet_10

LANGUAGE: TypeScript CODE:

// ✅ No error
 `'use client';`

import { Button, createTheme } from '@mantine/core';

export const theme = createTheme({
  components: {
    Button: Button.extend({}),
  },
});

TITLE: Setting Responsive AppShell Main Padding in React (TSX) DESCRIPTION: Illustrates applying responsive padding to the AppShell.Main area via the padding prop on the root AppShell component. An object maps breakpoints (base, sm, lg) to padding values (numbers, strings, or theme spacing tokens), similar to Mantine style props. Requires @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_8

LANGUAGE: tsx CODE:

import { AppShell } from '@mantine/core';

// Padding is:
// - 10 when viewport width is < theme.breakpoints.sm
// - 15 when viewport width is >= theme.breakpoints.sm and < theme.breakpoints.lg
// - theme.spacing.xl when viewport width is >= theme.breakpoints.lg
function Demo() {
  return (
    <AppShell padding={{ base: 10, sm: 15, lg: 'xl' }}>
      {/* AppShell content */}
    </AppShell>
  );
}

TITLE: Using setValues to Update Multiple Form Values at Once DESCRIPTION: Shows how to use the form.setValues method to update multiple form values at once. The payload is shallow merged with current values state. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/values.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { name: '', email: '', age: 0 },
});

form.setValues({ name: 'John', age: 21 });
form.getValues(); // -> { name: 'John', email: '', age: 21 }

TITLE: Implementing Accessibility for Burger Component DESCRIPTION: This snippet provides guidance on making the Burger component accessible for screen readers by setting 'aria-label' or including a visually hidden label with the VisuallyHidden component. It includes a sample implementation demonstrating both approaches. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/burger.mdx#_snippet_4

LANGUAGE: TypeScript CODE:

import { Burger, VisuallyHidden } from '@mantine/core';

function Demo() {
  return (
    <>
      <Burger aria-label="Toggle navigation" />

      <Burger>
        <VisuallyHidden>Toggle navigation</VisuallyHidden>
      </Burger>
    </>
  );
}

TITLE: Configuring FocusTrap for Initial Focus in Drawer DESCRIPTION: This code demonstrates adding 'data-autofocus' attribute for elements to receive initial focus when a Drawer opens. It also shows how to use 'FocusTrap.InitialFocus' for custom focus setup, ensuring accessibility and user experience considerations. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/drawer.mdx#_snippet_2

LANGUAGE: TSX CODE:

import { Drawer } from '@mantine/core';

function Demo() {
  return <Drawer title="Drawer label" opened onClose={() => {}} />;
}

TITLE: Checking Color Lightness with isLightColor in Mantine Core (TSX) DESCRIPTION: Example using the isLightColor function to determine if a given color string represents a light color. This is primarily used to dynamically set a contrasting text color ('black' or 'white') against a variable background color (bg) for better readability. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/color-functions.mdx#_snippet_6

LANGUAGE: tsx CODE:

import { Box, isLightColor } from '@mantine/core';

interface DemoProps {
  color: string;
}

export function Demo({ color }: DemoProps) {
  return (
    <Box bg={color} c={isLightColor(color) ? 'black' : 'white'}>
      Box with contrast text
    </Box>
  );
}

TITLE: Configuring Responsive AppShell Header Height in React (TSX) DESCRIPTION: Illustrates setting a responsive height for the AppShell.Header by passing an object to the header.height prop. The object keys represent Mantine theme breakpoints (base, sm, lg), and the values specify the header height for each corresponding viewport width range. Requires @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { AppShell } from '@mantine/core';

// Height is an object with breakpoints:
// - height is 48 when viewport width is < theme.breakpoints.sm
// - height is 60 when viewport width is >= theme.breakpoints.sm and < theme.breakpoints.lg
// - height is 76 when viewport width is >= theme.breakpoints.lg
function Demo() {
  return (
    <AppShell header={{ height: { base: 48, sm: 60, lg: 76 } }}>
      <AppShell.Header>Header</AppShell.Header>
    </AppShell>
  );
}

TITLE: Using getTreeExpandedState function DESCRIPTION: Demonstrates the usage of the getTreeExpandedState function to generate the expanded state object for the tree. The function accepts the tree data and an array of node values to expand. It provides options to expand specific nodes or expand all nodes. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tree.mdx#_snippet_10

LANGUAGE: tsx CODE:

// Expand two given nodes
getTreeExpandedState(data, ['src', 'src/components']);

// Expand all nodes
getTreeExpandedState(data, '*');

TITLE: Implementing Accessible PillsInput with label prop DESCRIPTION: This code snippet shows how to set the label prop on the PillsInput component to improve accessibility. It shows how to make the component accessible by providing a visible label. The output is an accessible PillsInput component. It requires the @mantine/core library. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/pills-input.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { PillsInput } from '@mantine/core';

// Accessible input – it has associated label element
function Demo() {
  return (
    <PillsInput label="Enter tags">
      <PillsInput.Field />
    </PillsInput>
  );
}

TITLE: Enhancing accessibility with InputAccessibility DESCRIPTION: This snippet demonstrates the use of 'InputAccessibility' API to improve ARIA attributes and assistive technology support, ensuring that TagsInput is accessible to all users. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tags-input.mdx#_snippet_27

LANGUAGE: TypeScript CODE:

<InputAccessibility component="TagsInput" />

TITLE: Using Mantine Box with Emotion sx Prop (React/TypeScript) DESCRIPTION: A client component demonstrating how to apply styles to a Mantine Box component using the sx prop with a function. The function receives the theme and utility functions (u) to apply different styles based on the color scheme (light mode). Note that components using sx, styles, or createStyles often require the 'use client' directive in the Next.js App Router. Requires @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_11

LANGUAGE: tsx CODE:

'use client';

import { Box } from '@mantine/core';

export default function HomePage() {
  return (
    <Box
      sx={(theme, u) => ({
        padding: 40,

        [u.light]: {
          backgroundColor: theme.colors.blue[0],
          color: theme.colors.blue[9],

          '&:hover': {
            backgroundColor: theme.colors.blue[1],
          },
        },
      })}
    >
      Box with emotion sx prop
    </Box>
  );
}

TITLE: Creating Mantine Form Actions (TSX) DESCRIPTION: This code shows how to create form actions using the createFormActions function from @mantine/form. You must provide the same form name used in useForm and the type of the form values to create actions that can interact with that specific form instance. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-2-0.mdx#_snippet_1

LANGUAGE: tsx CODE:

// Import type of form values from the file where you defined useForm
import { createFormActions } from '@mantine/form';
import type { DemoFormValues } from './DemoForm';

export const demoFormActions =
  createFormActions<DemoFormValues>('demo-form');

TITLE: Consuming Custom Mantine CSS Variables (CSS) DESCRIPTION: This CSS snippet illustrates how to consume the custom CSS variables defined via cssVariablesResolver in your application's stylesheets. It shows how --mantine-hero-height and --mantine-color-deep-orange can be used, with the latter automatically adapting its value based on the active color scheme. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_28

LANGUAGE: css CODE:

.hero {
  height: var(--mantine-hero-height);

  /* background color will automatically change based on color scheme */
  background-color: var(--mantine-color-deep-orange);
}

TITLE: Implementing Custom Tooltip Content in BarChart Using Recharts Tooltip Component, JSX/TypeScript DESCRIPTION: Allows passing a custom tooltip renderer via tooltipProps.content to the underlying Recharts Tooltip component. Requires filtering of recharts payload with a helper function to remove styling-only empty values. Demonstrated with BarChartDemos.customTooltip data. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/charts/bar-chart.mdx#_snippet_23

LANGUAGE: TSX CODE:

<Demo data={BarChartDemos.customTooltip} />

TITLE: Using CSS variables for dynamic pseudo-class styling DESCRIPTION: Demonstrates how to use CSS variables to apply dynamic styling to pseudo-classes like :hover, which can't be directly targeted with inline styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/dynamic-css-styles.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { Box } from '@mantine/core';
import classes from './Demo.module.css';

interface DemoProps {
  color: string;
}

function Demo({ color }: DemoProps) {
  return (
    <Box style={{ '--demo-hover': color }} className={classes.root}>
      My demo
    </Box>
  );
}

TITLE: Configuring Popover Detachment Behavior in Mantine TSX DESCRIPTION: Demonstrates the use of the hideDetached prop on the Mantine Popover component. The example shows two popovers, one with the default behavior (hidden when detached) and one with hideDetached={false} (visible when detached), illustrating how the prop controls dropdown visibility when the target is hidden or scrolled out of view. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/8.0.0.md#_snippet_2

LANGUAGE: tsx CODE:

import { Box, Button, Group, Popover } from '@mantine/core';

function Demo() {
  return (
    <Box
      bd="1px solid var(--mantine-color-dimmed)"
      p="xl"
      w={400}
      h={200}
      style={{ overflow: 'auto' }}
    >
      <Box w={1000} h={400}>
        <Group>
          <Popover width="target" position="bottom" opened>
            <Popover.Target>
              <Button>Toggle popover</Button>
            </Popover.Target>
            <Popover.Dropdown>This popover dropdown is hidden when detached</Popover.Dropdown>
          </Popover>

          <Popover width="target" position="bottom" opened hideDetached={false}>
            <Popover.Target>
              <Button>Toggle popover</Button>
            </Popover.Target>
            <Popover.Dropdown>This popover dropdown is visible when detached</Popover.Dropdown>
          </Popover>
        </Group>
      </Box>
    </Box>
  );
}

TITLE: Validating Nested Fields with Yup and useForm DESCRIPTION: This snippet demonstrates how to validate nested fields using Yup with Mantine Form. It defines a Yup schema for a nested object and uses yupResolver to integrate it with useForm. The example includes how to access the corresponding validation errors. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { yupResolver } from 'mantine-form-yup-resolver';
import * as yup from 'yup';
import { useForm } from '@mantine/form';

const nestedSchema = yup.object().shape({
  nested: yup.object().shape({
    field: yup
      .string()
      .min(2, 'Field should have at least 2 letters'),
  }),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    nested: {
      field: '',
    },
  },
  validate: yupResolver(nestedSchema),
});

form.validate();
form.errors;
// -> {
//  'nested.field': 'Field should have at least 2 letters',
// }

TITLE: Implementing Mantine Table with Compound Components (TSX) DESCRIPTION: Shows how to structure a table using the new compound component pattern, including Table.Thead, Table.Tbody, Table.Tr, and Table.Td, and mapping data to generate table rows. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_18

LANGUAGE: TSX CODE:

import { Table } from '@mantine/core';

function Demo() {
  const rows = elements.map((element) => (
    <Table.Tr key={element.name}>
      <Table.Td>{element.position}</Table.Td>
      <Table.Td>{element.name}</Table.Td>
      <Table.Td>{element.symbol}</Table.Td>
      <Table.Td>{element.mass}</Table.Td>
    </Table.Tr>
  ));

  return (
    <Table>
      <Table.Thead>
        <Table.Tr>
          <Table.Th>Element position</Table.Th>
          <Table.Th>Element name</Table.Th>
          <Table.Th>Symbol</Table.Th>
          <Table.Th>Atomic mass</Table.Th>
        </Table.Tr>
      </Table.Thead>
      <Table.Tbody>{rows}</Table.Tbody>
    </Table>
  );
}

TITLE: Showing Mantine Notification with Props (TSX) DESCRIPTION: Provides examples of using the notifications.show function to display notifications. It shows the minimum required message prop and a more complex example utilizing various optional properties like id, position, autoClose, title, color, icon, and styling props. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/notifications.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { IconX } from '@tabler/icons-react';
import { notifications } from '@mantine/notifications';

// Bare minimum – message is required for all notifications
notifications.show({ message: 'Hello' });

// Most used notification props
notifications.show({
  id: 'hello-there',
  position: 'bottom-center',
  withCloseButton: true,
  onClose: () => console.log('unmounted'),
  onOpen: () => console.log('mounted'),
  autoClose: 5000,
  title: "You've been compromised",
  message: 'Leave the building immediately',
  color: 'red',
  icon: <IconX />,
  className: 'my-notification-class',
  style: { backgroundColor: 'red' },
  loading: false,
});

TITLE: Using withErrorStyles Prop in Mantine TextInput (TSX) DESCRIPTION: Demonstrates how to use the withErrorStyles prop on Mantine inputs to disable default error styling. Shows an example with TextInput where default error styles are removed, allowing for custom error indication like adding an icon in the right section. Compares this approach with standard boolean and React node error handling. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_28

LANGUAGE: tsx CODE:

import { IconExclamationCircle } from '@tabler/icons-react';
import { rem, TextInput } from '@mantine/core';

function Demo() {
  return (
    <>
      <TextInput placeholder="Error as boolean" label="Error as boolean" error />
      <TextInput
        mt="md"
        placeholder="Error as react node"
        label="Error as react node"
        error="Something went wrong"
      />

      <TextInput
        mt="md"
        placeholder="Without error styles on input"
        label="Without error styles on input"
        error="Something went wrong"
        withErrorStyles={false}
        rightSectionPointerEvents="none"
        rightSection={
          <IconExclamationCircle
            style={{ width: rem(20), height: rem(20) }}
            color="var(--mantine-color-error)"
          />
        }
      />
    </>
  );
}

TITLE: Configuring Jest Setup File in JS DESCRIPTION: Shows how to add the path to the jest.setup.js file in the Jest configuration (jest.config.js) using the setupFilesAfterEnv array. This ensures the setup file, containing browser API mocks and other setup logic, is executed after the test environment is initialized and before test files are run. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/jest.mdx#_snippet_4

LANGUAGE: js CODE:

const config = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  // ... rest of your config
};

TITLE: Creating Controlled Chip Groups in Mantine with Single and Multiple Selection DESCRIPTION: This example shows how to implement both single selection (radio button behavior) and multiple selection (checkbox behavior) with Chip.Group. It demonstrates state management for both scenarios, including the different value types needed for each selection mode. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/chip.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Chip } from '@mantine/core';

function Single() {
  // string value when multiple is false (default)
  const [value, setValue] = useState('react');

  return (
    <Chip.Group multiple={false} value={value} onChange={setValue}>
      <Chip value="react">React</Chip>
      <Chip value="ng">Angular</Chip>
      <Chip value="svelte">Svelte</Chip>
      <Chip value="vue">Vue</Chip>
    </Chip.Group>
  );
}

function Multiple() {
  // array of strings value when multiple is true
  const [value, setValue] = useState(['react']);

  return (
    <Chip.Group multiple value={value} onChange={setValue}>
      <Chip value="react">React</Chip>
      <Chip value="ng">Angular</Chip>
      <Chip value="svelte">Svelte</Chip>
      <Chip value="vue">Vue</Chip>
    </Chip.Group>
  );
}

TITLE: Using CSS Modules in Mantine Component (TSX) DESCRIPTION: Shows how to import and use styles defined in a CSS module file within a React component, applying class names dynamically based on component state or props. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/styles-overview.mdx#_snippet_6

LANGUAGE: tsx CODE:

// Demo.tsx
import classes from './Demo.module.css';

function Demo({ collapsed }: { collapsed: boolean }) {
  return (
    <div
      className={classes.root}
      data-collapsed={collapsed || undefined}
    >
      <button type="button" className={classes.control}>
        Control
      </button>
    </div>
  );
}

TITLE: Controlled Search Value Management in MultiSelect with React Hooks in TypeScript DESCRIPTION: Illustrates controlling the searchable state of the MultiSelect component by managing the search input value explicitly via useState and passing searchValue and onSearchChange props. This approach allows customizing and synchronizing the search input externally. Required dependencies include React and @mantine/core, and it is implemented in TypeScript. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/multi-select.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { MultiSelect } from '@mantine/core';

function Demo() {
  const [searchValue, setSearchValue] = useState('');
  return (
    <MultiSelect
      searchable
      searchValue={searchValue}
      onSearchChange={setSearchValue}
      data={[]}
    />
  );
}

TITLE: Defining useColorScheme Hook - TypeScript DESCRIPTION: This TypeScript snippet defines the useColorScheme hook's function signature. It specifies the input parameters and the return type. The hook can take an optional initialValue parameter, which can be either 'dark' or 'light'. It also accepts an options object to configure its behavior and returns either 'dark' or 'light' representing the current color scheme. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-color-scheme.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

function useColorScheme(
  initialValue?: 'dark' | 'light',
  options?: {
    getInitialValueInEffect: boolean;
  }
): 'dark' | 'light';

TITLE: Configuring Mantine Theme for Local Fonts in TSX DESCRIPTION: This TSX snippet demonstrates how to configure a Mantine theme (createTheme) to use a locally loaded font ('Roboto') by setting fontFamily and headings.fontFamily. It also shows importing the local CSS file and wrapping the application with MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/vite-load-fonts.mdx#_snippet_1

LANGUAGE: tsx CODE:

import {
  createTheme,
  DEFAULT_THEME,
  MantineProvider,
} from '@mantine/core';

import '@mantine/core/styles.css';
import './Roboto/Roboto.css';

const theme = createTheme({
  fontFamily: 'Roboto, sans-serif',
  fontFamilyMonospace: 'Monaco, Courier, monospace',
  headings: {
    // Use default theme if you want to provide default Mantine fonts as a fallback
    fontFamily: `Roboto, ${DEFAULT_THEME.fontFamily}`,
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>Your app here</MantineProvider>
  );
}

TITLE: Apply CSS @font-face Font to Mantine Theme (TSX) DESCRIPTION: Imports a CSS file containing @font-face rules and creates a Mantine theme object, setting the fontFamily and headings.fontFamily properties to the font family name defined in the CSS. Wraps the application in MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/next-load-fonts.mdx#_snippet_3

LANGUAGE: tsx CODE:

import {
  createTheme,
  DEFAULT_THEME,
  MantineProvider,
} from '@mantine/core';

import '@mantine/core/styles.css';
import './Roboto/Roboto.css';

const theme = createTheme({
  fontFamily: 'Roboto, sans-serif',
  fontFamilyMonospace: 'Monaco, Courier, monospace',
  headings: {
    // Use default theme if you want to provide default Mantine fonts as a fallback
    fontFamily: `Roboto, ${DEFAULT_THEME.fontFamily}`,
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>Your app here</MantineProvider>
  );
}

TITLE: Importing Mantine Charts Styles (tsx) DESCRIPTION: Imports the necessary CSS styles for the @mantine/charts components. This step is crucial after installation to ensure components are rendered correctly with proper styling and layout. It should be done at the root of your application. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/charts/getting-started.mdx#_snippet_0

LANGUAGE: tsx CODE:

import '@mantine/charts/styles.css';

TITLE: Usage demonstration of LineChart component with data DESCRIPTION: Shows how to include the LineChart component with sample usage data. Dependencies include the LineChartDemos object containing predefined demo data. This snippet demonstrates rendering the chart with default or specific datasets. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/charts/line-chart.mdx#_snippet_1

LANGUAGE: JavaScript CODE:

<Demo data={LineChartDemos.usage} />

TITLE: Setting Default Color Scheme with MantineProvider (TSX) DESCRIPTION: Wrap your application with MantineProvider and use the defaultColorScheme prop to set the initial color scheme to 'light', 'dark', or 'auto'. The default value is 'light'. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/color-schemes.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { MantineProvider } from '@mantine/core';

function Demo() {
  return (
    <MantineProvider defaultColorScheme="dark">
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Using Debounced Callback with Mantine and React (TSX) DESCRIPTION: Demonstrates how to use the useDebouncedCallback hook from @mantine/hooks to perform a debounced search. It sets up React state to manage the search input, results, and loading state, with asynchronous logic to fetch and display mock search results. Dependencies include @mantine/core, @mantine/hooks, and React, and inputs/outputs are managed through the TextInput and result mapping. The debounce delay is set to 500ms, and an artificial delay is used for async simulation. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.8.0.md#_snippet_9

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Loader, Text, TextInput } from '@mantine/core';
import { useDebouncedCallback } from '@mantine/hooks';

function getSearchResults(query: string): Promise<{ id: number; title: string }[]> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(
        query.trim() === ''
          ? []
          : Array(5)
              .fill(0)
              .map((_, index) => ({ id: index, title: `${query} ${index + 1}` }))
      );
    }, 1000);
  });
}

function Demo() {
  const [search, setSearch] = useState('');
  const [searchResults, setSearchResults] = useState<{ id: number; title: string }[]>([]);
  const [loading, setLoading] = useState(false);

  const handleSearch = useDebouncedCallback(async (query: string) => {
    setLoading(true);
    setSearchResults(await getSearchResults(query));
    setLoading(false);
  }, 500);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(event.currentTarget.value);
    handleSearch(event.currentTarget.value);
  };

  return (
    <>
      <TextInput
        value={search}
        onChange={handleChange}
        placeholder="Search..."
        rightSection={loading && <Loader size={20} />}
      />
      {searchResults.map((result) => (
        <Text key={result.id} size="sm">
          {result.title}
        </Text>
      ))}
    </>
  );
}

TITLE: Add Emotion Types for Mantine Props (TSX) DESCRIPTION: Create this declaration file to extend Mantine's core types, adding support for Emotion's sx and styles props on components like Box. This enables type checking and autocompletion for Emotion-specific styling within your TypeScript project. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_0

LANGUAGE: tsx CODE:

import '@mantine/core';

import type { EmotionStyles, EmotionSx } from '@mantine/emotion';

declare module '@mantine/core' {
  export interface BoxProps {
    sx?: EmotionSx;
    styles?: EmotionStyles;
  }
}

TITLE: Importing FormErrors Type – Mantine DESCRIPTION: Shows how to import the FormErrors type from @mantine/form for type checking. Also shows how to get the type directly from the form instance. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/errors.mdx#_snippet_8

LANGUAGE: tsx CODE:

import type { FormErrors } from '@mantine/form';

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled' });

const handleErrors = (errors: typeof form.errors) => {};

TITLE: TypeScript Definition of useUncontrolled Hook DESCRIPTION: Provides the TypeScript interface UseUncontrolledInput<T> which defines the accepted parameters (value, defaultValue, finalValue, onChange) for the hook, and the function signature showing the returned tuple: the current value (T), the change handler function (value: T) => void, and a boolean indicating if the component is controlled. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-uncontrolled.mdx#_snippet_2

LANGUAGE: tsx CODE:

interface UseUncontrolledInput<T> {
  /** Value for controlled state */
  value?: T;

  /** Initial value for uncontrolled state */
  defaultValue?: T;

  /** Final value for uncontrolled state when value and defaultValue are not provided */
  finalValue?: T;

  /** Controlled state onChange handler */
  onChange?: (value: T) => void;
}

function useUncontrolled<T>(input: UseUncontrolledInput<T>): [
  T, // current value
  (value: T) => void, // onChange function
  boolean, // value that indicates if input is controlled or not
];

TITLE: Using useLocalStorage with SuperJSON for Advanced Types in React DESCRIPTION: Shows how to integrate the SuperJSON library with useLocalStorage hook to handle complex JavaScript types like Date, Map, Set, and BigInt that are not supported by standard JSON serialization. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-local-storage.mdx#_snippet_4

LANGUAGE: tsx CODE:

import superjson from 'superjson';
import { useLocalStorage } from '@mantine/hooks';

const defaultValue = { name: 'John', age: 25 };

const [value, setValue] = useLocalStorage({
  key: 'data',
  defaultValue,
  serialize: superjson.stringify,
  deserialize: (str) =>
    str === undefined ? defaultValue : superjson.parse(str),
});

TITLE: Opening and Closing Typesafe Context Modals Programmatically in TypeScript DESCRIPTION: Demonstrates usage of openContextModal and closeModal functions from @mantine/modals to open and close a typesafe context modal identified by modal key 'demonstration'. openContextModal accepts a configuration object including modal key, title, and typed innerProps to pass data securely. This pattern supports programmatic modal lifecycle management with type-checked props. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/x/modals.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { closeModal, openContextModal } from '@mantine/modals';

openContextModal({
  modal: 'demonstration',
  title: 'Test modal from context',
  innerProps: {
    modalBody:
      'This modal was defined in ModalsProvider, you can open it anywhere in you app with useModals hook',
  },
});
closeModal('demonstration');

TITLE: Customize Heading Styles with Mantine Theme (TSX) DESCRIPTION: Illustrates how to apply custom styles to h1-h6 headings used in Mantine components like Title and TypographyStylesProvider by defining the headings property in the theme, allowing configuration of font weight, font family, font size, and line height globally or per heading level. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/typography.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider, rem } from '@mantine/core';

const theme = createTheme({
  headings: {
    // properties for all headings
    fontWeight: '400',
    fontFamily: 'Roboto',

    // properties for individual headings, all of them are optional
    sizes: {
      h1: {
        fontWeight: '100',
        fontSize: 36,
        lineHeight: '1.4',
      },
      h2: { fontSize: 30, lineHeight: '1.5' },
      // ...up to h6
      h6: { fontWeight: '900' },
    },
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Using useStateHistory Hook in Mantine (TSX) DESCRIPTION: Illustrates the usage of the useStateHistory hook to manage state with built-in history tracking, allowing for undo and redo operations. It shows how to set a new value, go back to a previous value, and go forward. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.7.0.md#_snippet_5

LANGUAGE: tsx CODE:

import { Button, Code, Group, Text } from '@mantine/core';
import { useStateHistory } from '@mantine/hooks';

function Demo() {
  const [value, handlers, history] = useStateHistory(1);
  return (
    <>
      <Text>Current value: {value}</Text>
      <Group my="md">
        <Button onClick={() => handlers.set(Math.ceil(Math.random() * 100) + 1)}>Set value</Button>
        <Button onClick={() => handlers.back()}>Back</Button>
        <Button onClick={() => handlers.forward()}>Forward</Button>
      </Group>
      <Code block>{JSON.stringify(history, null, 2)}</Code>
    </>
  );
}

TITLE: Definition of Mantine mantineHtmlProps Object DESCRIPTION: This snippet shows the structure of the mantineHtmlProps object provided by Mantine. It contains suppressHydrationWarning to prevent the warning on the <html> element and a default data-mantine-color-scheme value. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/color-scheme-hydration-warning.mdx#_snippet_3

LANGUAGE: tsx CODE:

export const mantineHtmlProps = {
  suppressHydrationWarning: true,
  'data-mantine-color-scheme': 'light',
};

TITLE: Using the useMounted Hook from Mantine Hooks in TypeScript DESCRIPTION: This snippet demonstrates how to import and use the useMounted hook from the @mantine/hooks library within a React functional component written in TypeScript. The hook returns a boolean indicating if the component is currently mounted, which enables conditional rendering. The demonstration includes a component that displays 'Component is mounted' when mounted and 'Component is not mounted' otherwise. Prerequisites include React and the Mantine hooks package installed and available. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-mounted.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useMounted } from '@mantine/hooks';

function Demo() {
  const mounted = useMounted();
  return (
    <div>
      {mounted ? 'Component is mounted' : 'Component is not mounted'}
    </div>
  );
}

TITLE: Animating Button Loading State (Mantine Button, TypeScript) DESCRIPTION: Demonstrates handling a loading animation state in Mantine Button components using the loading prop, coupled with a Switch for toggling. Requires '@mantine/core', useDisclosure hook, and a Switch component. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.3.0.md#_snippet_11

LANGUAGE: tsx CODE:

import { Button, Group } from '@mantine/core';

function Demo() {
  const [loading, { toggle }] = useDisclosure();
  return (
    <>
      <Group>
        <Button loading={loading}>Filled button</Button>
        <Button variant="light" loading={loading}>
          Light button
        </Button>
        <Button variant="outline" loading={loading}>
          Outline button
        </Button>
      </Group>

      <Switch checked={loading} onChange={toggle} label="Loading state" mt="md" />
    </>
  );
}

TITLE: Setting Form Errors with setErrors – Mantine DESCRIPTION: Illustrates how to use the form.setErrors handler to set multiple errors at once. The handler takes an object where keys are field names and values are the error messages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/errors.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({ mode: 'uncontrolled' });
form.setErrors({ firstName: 'Too short', email: 'Invalid email' });

form.errors;
// -> { firstName: 'Too short', email: 'Invalid email' }


TITLE: Clearing All Form Errors with clearErrors – Mantine DESCRIPTION: Shows how to clear all existing form errors using the form.clearErrors handler. This can be used to reset the error state when the form is submitted or when input values change. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/errors.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialErrors: { name: 'Too short', email: 'Invalid email' },
});

form.clearErrors();

form.errors; // -> {}


TITLE: Migrating theme.colorScheme with @mantine/emotion DESCRIPTION: Shows how to transition from using theme.colorScheme in 6.x to using light/dark utilities in @mantine/emotion in 7.x. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/6x-to-7x.mdx#_snippet_2

LANGUAGE: tsx CODE:

// 6.x
import { createStyles } from '@mantine/core';

const useStyles = createStyles((theme) => ({
  root: {
    backgroundColor:
      theme.colorScheme === 'dark'
        ? theme.colors.dark[6]
        : theme.colors.gray[0],
    color: theme.colorScheme === 'dark' ? theme.white : theme.black,
  },
}));

LANGUAGE: tsx CODE:

// 7.x
import { createStyles } from '@mantine/emotion';

const useStyles = createStyles((theme, _, u) => ({
  root: {
    [u.dark] {
      backgroundColor: theme.colors.dark[6];
      color: theme.white;
    },

    [u.light]: {
      backgroundColor: theme.colors.gray[0];
      color: theme.black;
    },
  },
}));

TITLE: Migrating Global component to CSS files DESCRIPTION: Shows how to migrate from Global component in 6.x to a regular CSS file in 7.x for applying global styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/6x-to-7x.mdx#_snippet_8

LANGUAGE: tsx CODE:

// 6.x
import { Global } from '@mantine/core';

function Demo() {
  return (
    <Global
      styles={(theme) => ({
        '*, *::before, *::after': {
          boxSizing: 'border-box',
        },

        body: {
          backgroundColor:
            theme.colorScheme === 'dark'
              ? theme.colors.dark[7]
              : theme.white,
          color:
            theme.colorScheme === 'dark'
              ? theme.colors.dark[0]
              : theme.black,
          lineHeight: theme.lineHeight,
        },

        '.your-class': {
          backgroundColor: 'red',
        },

        '#your-id > [data-active]': {
          backgroundColor: 'pink',
        },
      })}
    />
  );
}

LANGUAGE: scss CODE:

/* 7.0 */
/* src/index.css */
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  background-color: light-dark(
    var(--mantine-color-white),
    var(--mantine-color-dark-7)
  );
  color: light-dark(
    var(--mantine-color-black),
    var(--mantine-color-white)
  );
  line-height: var(--mantine-line-height);
}

.your-class {
  background-color: red;
}

#your-id > [data-active] {
  background-color: pink;
}

TITLE: Reordering Items in a List with useListState DESCRIPTION: The reorder handler moves an item from one position to another within the list. It takes an object with from and to properties, indicating the starting and ending indices of the move. In this example item at index 2 is moved to index 0. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-list-state.mdx#_snippet_6

LANGUAGE: tsx CODE:

// move item from one position to another
const reorder = () => handlers.reorder({ from: 2, to: 0 });
// values -> [{ a: 4 }, { a: 0 }, { a: 5 }]

TITLE: Merging Multiple Theme Overrides DESCRIPTION: Illustrates how to combine multiple theme override objects into a single object using the mergeThemeOverrides function from @mantine/core before applying the merged theme to the MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/theme-object.mdx#_snippet_6

LANGUAGE: tsx CODE:

import {
  createTheme,
  MantineProvider,
  mergeThemeOverrides,
} from '@mantine/core';

const theme1 = createTheme({
  primaryColor: 'orange',
  defaultRadius: 0,
});

const theme2 = createTheme({
  cursorType: 'pointer',
});

// Note: It is better to to store theme override outside of component body
// to prevent unnecessary re-renders
const myTheme = mergeThemeOverrides(theme1, theme2);

function Demo() {
  return (
    <MantineProvider theme={myTheme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Type Specification with useLocalStorage in TypeScript DESCRIPTION: Demonstrates how to specify the type of the stored value when using useLocalStorage hook with TypeScript, providing type safety and better autocompletion. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-local-storage.mdx#_snippet_6

LANGUAGE: tsx CODE:

import { useLocalStorage } from '@mantine/hooks';

const [value, setValue] = useLocalStorage<'dark' | 'light'>({
  key: 'color-scheme',
  defaultValue: 'light',
});

TITLE: Updating Mantine Dependencies with npm-check-updates DESCRIPTION: Uses npx to run npm-check-updates to automatically update Mantine-related dependencies in package.json. This command targets @mantine/, @mantinex/, and postcss-preset-mantine packages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/how-to-update-dependencies.mdx#_snippet_0

LANGUAGE: sh CODE:

npx npm-check-updates @mantine/* @mantinex/* postcss-preset-mantine -u

TITLE: Configuring Fixed AppShell Navbar Width in React (TSX) DESCRIPTION: Example showing how to set a fixed width for the AppShell.Navbar using a number in the navbar.width prop, effective only when the viewport is wider than the specified navbar.breakpoint. Below the breakpoint, the navbar width defaults to 100%. Requires @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { AppShell } from '@mantine/core';

// Width is a number, it will be converted to rem
// and used as width when viewport is larger than theme.breakpoints.sm
function Demo() {
  return (
    <AppShell navbar={{ width: 48, breakpoint: 'sm' }}>
      <AppShell.Navbar>Navbar</AppShell.Navbar>
    </AppShell>
  );
}

TITLE: Using TagsInput within a Popover component DESCRIPTION: This snippet shows how to embed TagsInput inside a Popover by setting 'withinPortal' to false, enabling the dropdown to render within the existing DOM hierarchy for correct positioning. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tags-input.mdx#_snippet_13

LANGUAGE: TypeScript CODE:

<Demo data={TagsInputDemos.withinPopover} />

TITLE: Incorrect Import Order for Dependent Styles in Mantine (tsx) DESCRIPTION: Illustrates the incorrect order for importing CSS files when one component depends on another. Importing the dependent component's styles (e.g., Button) before the base component's styles (e.g., UnstyledButton) can lead to the base styles incorrectly overriding the dependent component's specific styles. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-files-list.mdx#_snippet_4

LANGUAGE: tsx CODE:

// ❌ Incorrect order – UnstyledButton styles will override Button styles
import '@mantine/core/styles/Button.css';
import '@mantine/core/styles/UnstyledButton.css';

TITLE: Configuring useCombobox Hook with Event Handlers in Mantine (TypeScript) DESCRIPTION: Shows configuring the useCombobox hook with onDropdownOpen and onDropdownClose event handlers that invoke store methods to select the first option when opening and reset selected option when closing the dropdown. This pattern enhances responsive UI behavior for dropdown opening and closing events. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/combobox.mdx#_snippet_4

LANGUAGE: tsx CODE:

import { Combobox, useCombobox } from '@mantine/core';

function Demo() {
  const combobox = useCombobox({
    onDropdownOpen: () => combobox.selectFirstOption(),
    onDropdownClose: () => combobox.resetSelectedOption(),
  });

  return (
    <Combobox store={combobox}>{/* Your implementation */}</Combobox>
  );
}

TITLE: Configure Line Heights with Mantine Theme (TSX) DESCRIPTION: Shows how to set custom line height values for Mantine components, particularly the Text component, by configuring the lineHeights property in the theme object created with createTheme and wrapping the application in MantineProvider. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/typography.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  lineHeights: {
    xs: '1.4',
    sm: '1.45',
    md: '1.55',
    lg: '1.6',
    xl: '1.65',
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      {/* Your app here */}
    </MantineProvider>
  );
}

TITLE: Applying textWrap setting globally via Mantine theme in TypeScript DESCRIPTION: Shows how to globally configure the 'textWrap' property for all heading components by setting it on the theme via createTheme and MantineProvider. This enforces consistent text wrapping behavior application-wide without setting the prop on individual components. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.5.0.md#_snippet_7

LANGUAGE: tsx CODE:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  headings: {
    textWrap: 'wrap'
  },
});

function Demo() {
  return (
    <MantineProvider theme={theme}>
      <Title>Some very long title that should wrap</Title>
    </MantineProvider>
  );
}

TITLE: Accessing Theme with useMantineTheme Hook DESCRIPTION: Demonstrates using the useMantineTheme hook within a functional React component to access the theme object provided by the nearest MantineProvider context. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/theming/theme-object.mdx#_snippet_7

LANGUAGE: tsx CODE:

import { useMantineTheme } from '@mantine/core';

function Demo() {
  const theme = useMantineTheme();
  return <div style={{ background: theme.colors.blue[5] }} />;
}

TITLE: Applying Directional Styling with rtl and ltr Mixins - SCSS and CSS DESCRIPTION: Shows the use of rtl and ltr mixins to conditionally apply CSS rules depending on text direction, typically set via the dir attribute in HTML. These mixins generate selectors targeting the appropriate direction attribute on parent elements for styling right-to-left or left-to-right layouts, enabling flexible internationalization support. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/postcss-preset.mdx#_snippet_6

LANGUAGE: SCSS CODE:

.demo {
  margin-left: 1rem;

  @mixin rtl {
    margin-left: 0;
    margin-right: 1rem;
  }
}

LANGUAGE: CSS CODE:

.demo {
  margin-left: 1rem;
}

[dir='rtl'] .demo {
  margin-left: 0;
  margin-right: 1rem;
}

LANGUAGE: SCSS CODE:

.demo {
  margin-left: 1rem;

  @mixin ltr {
    margin-left: 0;
    margin-right: 1rem;
  }
}

LANGUAGE: CSS CODE:

.demo {
  margin-left: 1rem;
}

[dir='ltr'] .demo {
  margin-left: 0;
  margin-right: 1rem;
}

TITLE: Explaining PostCSS functions in Mantine styles with example usage DESCRIPTION: Provides an example of using the 'light-dark' PostCSS function in SCSS files, demonstrating how it simplifies theme-based styling by automatically adjusting styles based on color scheme. Highlights that PostCSS transformations are only applicable within stylesheet files. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/postcss-fns-inline.mdx#_snippet_1

LANGUAGE: scss CODE:

// What you write
.demo {
  background: light-dark(white, black);
}

// What you get after PostCSS processing
[data-mantine-color-scheme='light'] .demo {
  background: black;
}

[data-mantine-color-scheme='dark'] .demo {
  background: black;
}

TITLE: Preventing Modal from Closing using opened prop - JavaScript DESCRIPTION: This snippet explains the use of the opened prop of the Mantine Modal and Drawer components to prevent the modal from closing when the user clicks outside of it or presses the Escape key. It is useful when an async operation is in progress inside the modal. This involves setting the opened prop to true to keep the modal open. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/how-to-prevent-modal-from-closing.mdx#_snippet_0


TITLE: Style object with CSS variables in Mantine DESCRIPTION: Shows how to use a style object with Mantine CSS variables to style a Mantine Box component. Requires the @mantine/core package. Defines inline styles using CSS variables for color and font size. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/style.mdx#_snippet_0

LANGUAGE: typescript CODE:

import { Box, rem } from '@mantine/core';

function Demo() {
  return (
    <Box
      style={{
        color: 'var(--mantine-color-red-5)',
        fontSize: rem(12),
      }}
    />
  );
}

TITLE: Using useIntersection hook within a React component DESCRIPTION: Demonstrates practical application of the useIntersection hook within a React functional component, showing how to obtain the ref callback for observed elements and render them. It includes examples with a div and a Mantine Paper component, capturing intersection entries. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-intersection.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

function Demo() {
  const { ref } = useIntersection();

  return (
    <>
      {/* With regular element: */}
      <div ref={ref} />

      {/* With Mantine component: */}
      <Paper ref={ref} />
    </>
  );
}

TITLE: Using Left and Right Sections in Mantine Button (TSX) DESCRIPTION: This example demonstrates the usage of the leftSection and rightSection props on a Mantine Button component. These props allow placing content (like icons or text) on either side of the button's main label. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_16

LANGUAGE: tsx CODE:

import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button leftSection="left" rightSection="right">
      Label
    </Button>
  );
}

TITLE: Implementing Controlled FileInput (multiple files) in TypeScript DESCRIPTION: This snippet shows how to manage multiple file selection using the FileInput component. It utilizes the useState hook and the multiple prop. The value prop will be an array of File objects. The onChange prop updates the selected file array whenever a change occurs in the selection. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/file-input.mdx#_snippet_1

LANGUAGE: tsx CODE:

```tsx
import { useState } from 'react';
import { FileInput } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState<File[]>([]);
  return <FileInput multiple value={value} onChange={setValue} />;
}

----------------------------------------

TITLE: Mantine Primary Color CSS Variables
DESCRIPTION: These CSS variables provide access to the different shades and states of the configured primary color within Mantine, allowing for consistent styling across applications.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-4-0.mdx#_snippet_7

LANGUAGE: scss
CODE:

--mantine-primary-color-0 --mantine-primary-color-1 --mantine-primary-color-2 --mantine-primary-color-3 --mantine-primary-color-4 --mantine-primary-color-5 --mantine-primary-color-6 --mantine-primary-color-7 --mantine-primary-color-8 --mantine-primary-color-9 --mantine-primary-color-contrast --mantine-primary-color-filled --mantine-primary-color-filled-hover --mantine-primary-color-light --mantine-primary-color-light-hover --mantine-primary-color-light-color


----------------------------------------

TITLE: Using Mantine Fieldset to Disable All Inputs in a Form (JavaScript)
DESCRIPTION: Demonstrates how to disable all input elements within a form by utilizing the Mantine Fieldset component. Setting the 'disabled' prop disables all nested inputs. The example also shows how to use the 'variant' prop to style the Fieldset as unstyled for only the disabled functionality.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/disable-all-inputs-in-form.mdx#_snippet_0

LANGUAGE: JavaScript
CODE:

import { EnhanceDisableInputs } from '@/demos/EnhanceDisableInputs.demo'; import { FieldsetInputs } from '@/demos/FieldsetInputs.demo'; import { Layout } from '@/layout';

export const meta = { title: 'How can I disable all inputs/inputs group inside form?', description: 'Learn how to disable all inputs/inputs group inside form with unstyled Fieldset component', slug: 'disable-all-inputs-in-form', category: 'forms', tags: ['form', 'inputs', 'Fieldset'], created_at: 'November 30, 2023', last_updated_at: 'July 15, 2023', };

export default Layout(meta);

// Usage of Fieldset: // Wrap form inputs with <Fieldset disabled={true}> to disable all nested inputs. // Set variant="unstyled" to remove default border and padding styles if only disabling functionality is desired.

// Example component to demonstrate usage: // <Demo data={FieldsetInputs} />


----------------------------------------

TITLE: Implementing Accessible Mantine Alert with Close Button (TypeScript/JavaScript)
DESCRIPTION: This snippet defines React components utilizing Mantine's Alert component with accessibility features, including labels for close buttons and ARIA attributes. It highlights best practices for accessible UI components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/alert.mdx#_snippet_2

LANGUAGE: TypeScript
CODE:

import { Alert } from '@mantine/core';

function Invalid() { // -> not ok return <Alert withCloseButton />; }

function Valid() { // -> ok return <Alert withCloseButton closeButtonLabel="Dismiss" />; }

function AlsoValid() { // -> ok, without close button, closeButtonLabel is not needed return <Alert />; }


----------------------------------------

TITLE: Custom Rendering React Components with MantineProvider in TSX
DESCRIPTION: Provides a custom `render` function using `@testing-library/react` that automatically wraps the tested component (`ui`) with `MantineProvider`. This is necessary because Mantine components require `MantineProvider` in the component tree. Requires `@testing-library/react` and `@mantine/core`, and a theme object.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/jest.mdx#_snippet_0

LANGUAGE: tsx
CODE:

// ./test-utils/render.tsx import { render as testingLibraryRender } from '@testing-library/react'; import { MantineProvider } from '@mantine/core'; // Import your theme object import { theme } from '../src/theme';

export function render(ui: React.ReactNode) { return testingLibraryRender(<>{ui}</>, { wrapper: ({ children }: { children: React.ReactNode }) => ( <MantineProvider theme={theme}>{children}</MantineProvider> ), }); }


----------------------------------------

TITLE: Defining useHover Hook in TypeScript
DESCRIPTION: This TypeScript snippet defines the `useHover` hook.  It takes a generic type `T` extending `HTMLElement` (defaults to `HTMLDivElement`) and returns an object containing a `ref` (React ref object) and a `hovered` boolean.  This hook is intended to track whether a particular HTML element is being hovered over by the mouse cursor.  The `ref` is for attaching the hook to a DOM element, while the `hovered` variable indicates its current state. No external dependencies are explicitly shown here.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-hover.mdx#_snippet_0

LANGUAGE: tsx
CODE:

function useHover<T extends HTMLElement = HTMLDivElement>(): { ref: React.RefObject<T>; hovered: boolean; };


----------------------------------------

TITLE: Basic Styling with Mantine Variables in Vanilla Extract (TypeScript)
DESCRIPTION: Demonstrates basic component styling using Vanilla Extract's `style` function. It accesses Mantine theme properties (like font sizes and colors) via the imported `vars` object generated by `themeToVars`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/vanilla-extract.mdx#_snippet_2

LANGUAGE: tsx
CODE:

// Demo.css.ts import { style } from '@vanilla-extract/css'; import { vars } from './theme';

export const demo = style({ fontSize: vars.fontSizes.xl, backgroundColor: vars.colors.red[5], color: vars.colors.white, });


----------------------------------------

TITLE: Importing Multiple Mantine Package Styles with CSS Layers (TSX)
DESCRIPTION: Demonstrates importing the new .layer.css files for different Mantine packages (@mantine/core, @mantine/dates). Notes that these replace the standard styles.css imports.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-1-0.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import '@mantine/core/styles.layer.css'; import '@mantine/dates/styles.layer.css';

// ... other styles


----------------------------------------

TITLE: Customizing Close Button via closeButtonProps
DESCRIPTION: This code highlights how to modify the close button's accessibility label using 'closeButtonProps', ensuring better accessibility compliance and allowing localization or descriptive labeling of the close button.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/drawer.mdx#_snippet_4

LANGUAGE: TSX
CODE:

import { Drawer } from '@mantine/core';

function Demo() { return ( <Drawer closeButtonProps={{ 'aria-label': 'Close drawer' }} opened onClose={() => {}} /> ); }


----------------------------------------

TITLE: Style Components Using data-variant Attribute (TSX/SCSS)
DESCRIPTION: Explains that all components now include a `data-variant` attribute on their root element, regardless of predefined variants. This allows styling components based on their variant directly in CSS, especially useful when defining custom variants via the theme. Includes the corresponding SCSS demonstrating styling based on `data-variant`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_7

LANGUAGE: tsx
CODE:

import { createTheme, Input, MantineProvider } from '@mantine/core'; import classes from './Demo.module.css';

// It is better to add new variants in theme.components // This way you will be able to use them in anywhere in the app const theme = createTheme({ components: { Input: Input.extend({ classNames: classes }), }, });

function Demo() { return ( <MantineProvider theme={theme}> <Input variant="underline" placeholder="Underline input" /> <Input variant="filled" placeholder="Filled input" mt="md" /> </MantineProvider> ); }


LANGUAGE: scss
CODE:

.input { &[data-variant='underline'] { border-bottom: rem(2px) solid; border-radius: 0; padding-left: 0; padding-right: 0;

@mixin light {
  border-color: var(--mantine-color-gray-3);
}

@mixin dark {
  border-color: var(--mantine-color-dark-3);
}

&:focus {
  border-color: var(--mantine-color-blue-filled);
}

} }


----------------------------------------

TITLE: Using color manipulation functions alpha and lighten with CSS variables and OKLCH in TypeScript
DESCRIPTION: Demonstrates the usage of improved color functions 'alpha' and 'lighten' from @mantine/core which now support CSS variables and OKLCH colors. The snippet shows how to import the functions and apply them to hex colors and CSS variables, returning valid CSS color expressions (standard RGBA or CSS color-mix). Requires @mantine/core and TypeScript environment. These functions replace older implementations to provide wider color model compatibility.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.4.0.md#_snippet_7

LANGUAGE: tsx
CODE:

import { alpha, lighten } from '@mantine/core';

alpha('#4578FC', 0.45); // -> rgba(69, 120, 252, 0.45) alpha('var(--mantine-color-gray-4)', 0.74); // -> color-mix(in srgb, var(--mantine-color-gray-4), transparent 26%)

lighten('#4578FC', 0.45); // -> #a3c1ff lighten('var(--mantine-color-gray-4)', 0.74); // -> color-mix(in srgb, var(--mantine-color-gray-4), white 74%)


----------------------------------------

TITLE: Setting dayjs Locale with DatesProvider (TSX)
DESCRIPTION: Demonstrates how to set the dayjs locale for Mantine dates components using the DatesProvider. It requires importing the specific locale module from dayjs (e.g., 'dayjs/locale/ru') and then passing the locale name to the settings.locale prop of the DatesProvider. This approach works in most environments.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/dates/getting-started.mdx#_snippet_2

LANGUAGE: tsx
CODE:

import 'dayjs/locale/ru';

import { DatesProvider } from '@mantine/dates';

function Demo() { return ( <DatesProvider settings={{ locale: 'ru' }}> {/* Your app */} </DatesProvider> ); }


----------------------------------------

TITLE: Usage Example Showing Media Query Subscription and Demo Integration
DESCRIPTION: Provides an example of how to render a demo component that responds to media query changes using the useMediaQuery hook, illustrating dynamic responsiveness in the UI.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-media-query.mdx#_snippet_1

LANGUAGE: Markdown
CODE:

<Demo data={HooksDemos.useMediaQueryDemo} />


----------------------------------------

TITLE: Replacing SCSS Mixins for Color Scheme in Mantine Components - SCSS
DESCRIPTION: This SCSS snippet demonstrates how to implement color scheme-based styling for Mantine components in CRA without relying on SCSS mixins. The example shows both the unsupported mixin syntax and a supported approach using attribute selectors to directly target data-mantine-color-scheme values. No additional dependencies are needed beyond basic SCSS/CSS. The input is a component class, and the output is targeted color overrides for light/dark modes. Limitation: SCSS mixins are not available; direct selectors must be used.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/can-i-use-mantine-with-cra.mdx#_snippet_1

LANGUAGE: scss
CODE:

// ❌ Does not work with Create React App .demo { @mixin light { color: red; }

@mixin dark { color: blue; } }

// ✅ Works with Create React App [data-mantine-color-scheme='light'] .demo { color: red; }

[data-mantine-color-scheme='dark'] .demo { color: blue; }


----------------------------------------

TITLE: Implementing Accessible PillsInput with aria-label
DESCRIPTION: This code snippet showcases how to make the `PillsInput` component accessible using the `aria-label` attribute on the `PillsInput.Field` component. The component is accessible because it has `aria-label` which makes it screen reader friendly. The component requires `@mantine/core` library.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/pills-input.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { PillsInput } from '@mantine/core';

// Accessible input – it has aria-label function Demo() { return ( <PillsInput> <PillsInput.Field aria-label="Enter tags" /> </PillsInput> ); }


----------------------------------------

TITLE: Managing Throttled State with Mantine's useThrottledState Hook (TSX)
DESCRIPTION: Shows how to manage an input field's value with throttling using useThrottledState from @mantine/hooks. The throttled state ensures that updates occur at most once per 1000ms, regardless of fast input changes. Requires @mantine/core and Mantine hooks; the controlled value is displayed live in a Text component, and input is from a TextInput element. No external data fetching occurs.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.8.0.md#_snippet_10

LANGUAGE: tsx
CODE:

import { Text, TextInput } from '@mantine/core'; import { useThrottledState } from '@mantine/hooks';

function Demo() { const [throttledValue, setThrottledValue] = useThrottledState('', 1000);

return ( <> <TextInput placeholder="Search" onChange={(event) => setThrottledValue(event.currentTarget.value)} /> <Text>Throttled value: {throttledValue || '–'}</Text> </> ); }


----------------------------------------

TITLE: onChange handler with object format
DESCRIPTION: This example demonstrates how to use the second argument of the `onChange` handler to get the selected option object. This is useful when you want to store the entire option object in the state, rather than just the value.  The example uses the ComboboxItem interface.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/select.mdx#_snippet_1

LANGUAGE: typescript
CODE:

import { useState } from 'react'; import { ComboboxItem, Select } from '@mantine/core';

function Demo() { const [value, setValue] = useState<ComboboxItem | null>(null); return ( <Select data={[{ value: 'react', label: 'React library' }]} value={value ? value.value : null} onChange={(_value, option) => setValue(option)} /> ); }


----------------------------------------

TITLE: Using Mantine Component Classes for Custom Elements (TSX)
DESCRIPTION: This example demonstrates how to access and apply the root CSS class of a Mantine component (`Button.classes.root`) to a native HTML element (`<button>`). This allows styling custom elements with Mantine's built-in styles.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_14

LANGUAGE: tsx
CODE:

import { Button } from '@mantine/core';

function Demo() { return <button type="button" className={Button.classes.root} />; }


----------------------------------------

TITLE: Replacing sx prop with className or style
DESCRIPTION: Shows how to migrate from sx prop in 6.x to className or style prop in 7.x for applying styles to components.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/6x-to-7x.mdx#_snippet_4

LANGUAGE: tsx
CODE:

// 6.x import { Box } from '@mantine/core';

function Demo() { return ( <Box sx={(theme) => ({ backgroundColor: theme.colors.red[5] })} /> ); }


LANGUAGE: tsx
CODE:

// 7.0 import { Box } from '@mantine/core';

function Demo() { return ( <Box style={{ backgroundColor: 'var(--mantine-color-red-5)' }} /> ); }


----------------------------------------

TITLE: Defining Navbar/Aside Configuration Interface in TypeScript
DESCRIPTION: Shows the TypeScript interface for configuring the `AppShell.Navbar` and `AppShell.Aside` components through the `navbar` and `aside` props on `AppShell`. It defines properties like `width` (number, string, or responsive object), the mandatory `breakpoint` for mobile switching, and an optional `collapsed` object with `desktop` and `mobile` states.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_2

LANGUAGE: tsx
CODE:

interface Configuration { /** Width of the section: number, string or ** object with breakpoints as keys and width as value */ width: AppShellSize | AppShellResponsiveSize;

/** Breakpoint at which section should switch to mobile mode ** In mobile mode the section always has 100% width and its ** collapsed state is controlled by the collapsed.mobile ** instead of collapsed.desktop */ breakpoint: MantineBreakpoint | (string & {}) | number;

/** Determines whether the section should be collapsed */ collapsed?: { desktop?: boolean; mobile?: boolean }; }


----------------------------------------

TITLE: Custom Serialization with useLocalStorage Hook in React
DESCRIPTION: Demonstrates how to provide custom serialization and deserialization functions to the useLocalStorage hook for handling data types that cannot be serialized with JSON.stringify by default.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-local-storage.mdx#_snippet_3

LANGUAGE: tsx
CODE:

import { useLocalStorage } from '@mantine/hooks';

const [value, setValue] = useLocalStorage({ key: 'color-scheme', serialize: (value) => { /* return value serialized to string / }, deserialize: (localStorageValue) => { / parse localStorage string value and return value */ }, });


----------------------------------------

TITLE: Defining CSS Variables in style Prop (TSX)
DESCRIPTION: Shows how the style prop in Mantine components now allows defining CSS variables. Demonstrates setting a --radius variable and using it within the same style object for borderRadius.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-1-0.mdx#_snippet_5

LANGUAGE: tsx
CODE:

import { Box } from '@mantine/core';

function Demo() { return ( <Box style={{ '--radius': '0.5rem', borderRadius: 'var(--radius)' }} /> ); }


----------------------------------------

TITLE: Adding Axis Labels to BarChart Axes in JSX/TypeScript
DESCRIPTION: Demonstrates how to apply text labels to the x-axis and y-axis using `xAxisLabel` and `yAxisLabel` props, enhancing chart readability. Uses BarChartDemos.axisLabels sample data.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/charts/bar-chart.mdx#_snippet_11

LANGUAGE: TSX
CODE:
<Demo data={BarChartDemos.axisLabels} /> ```

TITLE: Guidance on Importing Mantine Carousel Styles in TypeScript DESCRIPTION: This snippet explains that missing style imports for '@mantine/core' and '@mantine/carousel' can cause the Carousel component to render vertically or display incorrect controls. It provides the exact import statements to include in the root of the application to fix styling issues, improving component rendering and control placement. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/carousel-missing-styles.mdx#_snippet_1

LANGUAGE: TypeScript CODE:

import '@mantine/core/styles.css';
import '@mantine/carousel/styles.css';

TITLE: Rendering SegmentedControl with Array Data Formats DESCRIPTION: This snippet illustrates two data formats supported by the SegmentedControl component. The first uses an array of strings where the value and label are identical. The second employs an array of objects, allowing for distinct value and label properties, offering greater flexibility for customization. Dependencies: @mantine/core library. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/segmented-control.mdx#_snippet_1

LANGUAGE: tsx CODE:

```tsx
import { SegmentedControl } from '@mantine/core';

function ArrayOfStrings() {
  return (
    <SegmentedControl data={['React', 'Angular', 'Svelte', 'Vue']} />
  );
}

function ArrayOfObjects() {
  return (
    <SegmentedControl
      data={[
        { value: 'React', label: 'React' },
        { value: 'Angular', label: 'Angular' },
        { value: 'Svelte', label: 'Svelte' },
        { value: 'Vue', label: 'Vue' },
      ]}
    />
  );
}

----------------------------------------

TITLE: Implementing Menu with Submenus in Mantine TSX
DESCRIPTION: Shows how to create a nested menu structure using the new Menu.Sub, Menu.Sub.Target, and Menu.Sub.Dropdown components. This allows for multi-level menus within a single Mantine Menu instance.
SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/8.0.0.md#_snippet_1

LANGUAGE: tsx
CODE:

import { Button, Menu } from '@mantine/core';

function Demo() { return ( <Menu width={200} position="bottom-start"> <Menu.Target> <Button>Toggle Menu</Button> </Menu.Target>

  <Menu.Dropdown>
    <Menu.Item>Dashboard</Menu.Item>

    <Menu.Sub>
      <Menu.Sub.Target>
        <Menu.Sub.Item>Products</Menu.Sub.Item>
      </Menu.Sub.Target>

      <Menu.Sub.Dropdown>
        <Menu.Item>All products</Menu.Item>
        <Menu.Item>Categories</Menu.Item>
        <Menu.Item>Tags</Menu.Item>
        <Menu.Item>Attributes</Menu.Item>
        <Menu.Item>Shipping classes</Menu.Item>
      </Menu.Sub.Dropdown>
    </Menu.Sub>

    <Menu.Sub>
      <Menu.Sub.Target>
        <Menu.Sub.Item>Orders</Menu.Sub.Item>
      </Menu.Sub.Target>

      <Menu.Sub.Dropdown>
        <Menu.Item>Open</Menu.Item>
        <Menu.Item>Completed</Menu.Item>
        <Menu.Item>Cancelled</Menu.Item>
      </Menu.Sub.Dropdown>
    </Menu.Sub>

    <Menu.Sub>
      <Menu.Sub.Target>
        <Menu.Sub.Item>Settings</Menu.Sub.Item>
      </Menu.Sub.Target>

      <Menu.Sub.Dropdown>
        <Menu.Item>Profile</Menu.Item>
        <Menu.Item>Security</Menu.Item>
        <Menu.Item>Notifications</Menu.Item>
      </Menu.Sub.Dropdown>
    </Menu.Sub>
  </Menu.Dropdown>
</Menu>

); }


----------------------------------------

TITLE: Converting Mantine Theme to Vanilla Extract Variables (TypeScript)
DESCRIPTION: Imports a previously defined Mantine theme and uses the `themeToVars` function from `@mantine/vanilla-extract` to convert it into a CSS variables object. This `vars` object makes Mantine theme tokens accessible within Vanilla Extract's `.css.ts` files.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/vanilla-extract.mdx#_snippet_1

LANGUAGE: tsx
CODE:

// theme.css.ts import { theme } from './theme'; import { themeToVars } from '@mantine/vanilla-extract';

// CSS variables object, can be access in *.css.ts files export const vars = themeToVars(theme);


----------------------------------------

TITLE: Using Inline Styles and Styles Prop with Mantine Button Component in TypeScript/TSX
DESCRIPTION: Shows a Mantine Button component with attempts to apply nested inline styles through `style` and `styles` props. Demonstrates that simple inline styles like `backgroundColor` work but nested styles such as `&:hover` or attribute selectors do not function due to Mantine's styling implementation. Inputs are React components with style objects, outputs are visual styles applied partially. Requires @mantine/core installed.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/nested-inline-styles.mdx#_snippet_1

LANGUAGE: tsx
CODE:

import { Button } from '@mantine/core';

function Demo() { return ( <Button style={{ // ✅ This works backgroundColor: 'hotpink',

    // ❌ This does not work
    '&:hover': { color: 'lightgreen' },
  }}
  styles={{
    root: {
      // ✅ This works
      backgroundColor: 'hotpink',

      // ❌ This does not work
      '&[data-disabled]': { color: 'lightgreen' },
      '&:hover': { color: 'lightgreen' },
      '&:focus': { color: 'lightgreen' },
      '& span': { color: 'lightgreen' },
    },
  }}
>
  This has a hotpink background.
</Button>

); }


----------------------------------------

TITLE: Fixing FileButton issue with keepMounted - Mantine/React
DESCRIPTION: This snippet references an external demo component (`FileButtonMenuFix.demo`) that illustrates the first solution. It shows how setting the `keepMounted` prop on the `Menu` component prevents the `FileButton` from unmounting when the menu closes, allowing the `onChange` callback to fire.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/file-button-in-menu.mdx#_snippet_2

LANGUAGE: jsx
CODE:
<Demo data={FileButtonMenuFix} /> ```

TITLE: Disabling Popover hideDetached Default (8.x) DESCRIPTION: Shows how to override the new default behavior of Popover in Mantine 8.x, where it automatically closes when the target is detached. This example disables hideDetached globally via theme configuration. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/7x-to-8x.mdx#_snippet_13

LANGUAGE: tsx CODE:

import { createTheme, Popover } from '@mantine/core';

export const theme = createTheme({
  components: {
    Popover: Popover.extend({
      defaultProps: {
        // ✅ Disable hideDetached by default
        // if you want to keep the old behavior
        hideDetached: false,
      },
    }),
  }
});

TITLE: Validating List Fields with Joi and useForm DESCRIPTION: This snippet demonstrates validating list fields using Joi with Mantine Form. It defines a Joi schema for a list of objects, uses joiResolver, and accesses the validation results. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/schema-validation.mdx#_snippet_8

LANGUAGE: tsx CODE:

import Joi from 'joi';
import { joiResolver } from 'mantine-form-joi-resolver';
import { useForm } from '@mantine/form';

const listSchema = Joi.object({
  list: Joi.array().items(
    Joi.object({
      name: Joi.string().min(2).messages({
        'string.min': 'Name should have at least 2 letters',
        'string.empty': 'Name should have at least 2 letters',
      }),
    })
  ),
});

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    list: [{ name: '' }],
  },
  validate: joiResolver(listSchema),
});

form.validate();
form.errors;
// -> {
//  'list.0.name': 'Name should have at least 2 letters',
// }

TITLE: Applying Mantine Heading Variables with Style Props in TSX DESCRIPTION: This TypeScript React snippet shows how to apply Mantine's heading CSS variables to a Box component using the fz (font-size) and lh (line-height) style props. By setting fz='h1' and lh='h1', the component automatically uses the --mantine-h1-* variables for its text. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_14

LANGUAGE: tsx CODE:

import { Box } from '@mantine/core';

function Demo() {
  return (
    <Box fz="h1" lh="h1">
      This text uses --mantine-h1-* variables
    </Box>
  );
}

TITLE: Importing Multiple Mantine Package Styles with CSS Layers (TSX) DESCRIPTION: Shows how to import styles from multiple Mantine packages (@mantine/core, @mantine/dates) using their respective .layer.css files. This is the recommended approach when using CSS layers, replacing the standard .css imports. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.1.0.md#_snippet_1

LANGUAGE: tsx CODE:

import '@mantine/core/styles.layer.css';
import '@mantine/dates/styles.layer.css';
// ... other styles

TITLE: Configuring ESLint with Mantine and TypeScript DESCRIPTION: This snippet demonstrates how to configure your project's eslint.config.mjs file to utilize the eslint-config-mantine package alongside typescript-eslint. It imports the required configurations, spreads the mantine rules, and adds specific file patterns to be ignored by ESLint. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/eslint-config-mantine.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

import mantine from 'eslint-config-mantine';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  ...mantine,
  { ignores: ['**/*.{mjs,cjs,js,d.ts,d.mts}'] }
);

TITLE: Using Mantine useCombobox Store Handlers to Control Dropdown State in TypeScript DESCRIPTION: Illustrates controlling Combobox dropdown state by manually invoking store handlers like openDropdown from useCombobox. The example shows wrapping a button with Combobox.Target and opening the dropdown programmatically on button click, demonstrating interaction between store handlers and UI elements in a React component. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/combobox.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { Button, Combobox, useCombobox } from '@mantine/core';

function Demo() {
  const combobox = useCombobox();

  return (
    <Combobox>
      <Combobox.Target>
        <Button onClick={() => combobox.openDropdown()}>
          Open dropdown
        </Button>
      </Combobox.Target>

      {/* Your implementation */}
    </Combobox>
  );
}

TITLE: Comparing Form Field Values with Mantine matchesField Validator in TypeScript DESCRIPTION: This example demonstrates the matchesField validator that checks if a form field value matches the value of another specified field. It only works with primitive values and does not support array or object comparison. The snippet shows validation for confirming password equality using useForm in uncontrolled mode, returning a custom error if values differ. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validators.mdx#_snippet_5

LANGUAGE: tsx CODE:

import { matchesField, useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: {
    password: '',
    confirmPassword: '',
  },

  validate: {
    confirmPassword: matchesField(
      'password',
      'Passwords are not the same'
    ),
  },
});

TITLE: Simplified Light/Dark Mode Styling in Vanilla Extract (TypeScript) DESCRIPTION: Demonstrates a common pattern for handling light/dark mode styles in Vanilla Extract. Base styles (usually for light mode) are defined first, and then specific overrides for dark mode are applied using the vars.darkSelector within the selectors block. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/vanilla-extract.mdx#_snippet_5

LANGUAGE: tsx CODE:

// Demo.css.ts
import { style } from '@vanilla-extract/css';
import { vars } from './theme';

export const demo = style({
  fontSize: vars.fontSizes.xl,
  backgroundColor: vars.colors.red[5],
  color: vars.colors.white,

  selectors: {
    [vars.darkSelector]: {
      backgroundColor: vars.colors.blue[5],
      color: vars.colors.white,
    },
  },
});

TITLE: TypeScript Ref Typing with useClickOutside Hook DESCRIPTION: Demonstrates how to properly type the ref returned by useClickOutside when using TypeScript. This ensures type safety when working with the hook. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-click-outside.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { useClickOutside } from '@mantine/hooks';

const ref = useClickOutside<HTMLDivElement>(() =>
  console.log('Click outside')
);

TITLE: Implementing One-Time Code Input with PinInput in React DESCRIPTION: Demonstrates how to create a PIN input field with one-time code support for SMS verification. The oneTimeCode prop sets autocomplete="one-time-code" to interface with OS-level SMS code suggestions. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/pin-input.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { PinInput } from '@mantine/core';

function OneTimeCodeInput() {
  return <PinInput oneTimeCode />;
}

TITLE: Using useMantineColorScheme Hook DESCRIPTION: Illustrates how to use the useMantineColorScheme hook, part of the built-in color scheme manager in Mantine v7. It provides functions like setColorScheme and clearColorScheme to programmatically change the application's color scheme. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.0.0.md#_snippet_2

LANGUAGE: tsx CODE:

import { Button, Group, useMantineColorScheme } from '@mantine/core';

function Demo() {
  const { setColorScheme, clearColorScheme } = useMantineColorScheme();

  return (
    <Group>
      <Button onClick={() => setColorScheme('light')}>Light</Button>
      <Button onClick={() => setColorScheme('dark')}>Dark</Button>
      <Button onClick={() => setColorScheme('auto')}>Auto</Button>
      <Button onClick={clearColorScheme}>Clear</Button>
    </Group>
  );
}

TITLE: Creating a Disabled Button in TypeScript DESCRIPTION: This code snippet demonstrates the creation of a disabled button using the Mantine UI library. The disabled prop is set to true, which adds the data-disabled attribute to the HTML button element. This attribute can be used to apply specific styles for the disabled state. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/data-attributes.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { Button } from '@mantine/core';

function Demo() {
  return (
    <Button disabled className="my-button">
      Disabled button
    </Button>
  );
}


TITLE: Applying a Function Conditionally to List Items with useListState DESCRIPTION: The applyWhere handler applies a function to elements of the list that satisfy a given condition. It accepts a condition function and an update function. The condition is met if a is greater than 0, then a is incremented by 2. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-list-state.mdx#_snippet_8

LANGUAGE: tsx CODE:

// apply function to each element that matches condition
const applyWhere = () =>
  handlers.applyWhere(
    (item) => item.a > 0,
    (item) => ({ a: item.a + 2 })
  );
// values -> [{ a: 7 }, { a: 0 }, { a: 6 }]

TITLE: Adding Axis Labels to Mantine AreaChart (TSX) DESCRIPTION: Demonstrates how to add labels to the X and Y axes of the AreaChart component using the new xAxisLabel and yAxisLabel props. This enhances the readability of the chart. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.7.0.md#_snippet_6

LANGUAGE: tsx CODE:

import { AreaChart } from '@mantine/charts';
import { data } from './data';

function Demo() {
  return (
    <AreaChart
      h={300}
      data={data}
      dataKey="date"
      type="stacked"
      xAxisLabel="Date"
      yAxisLabel="Amount"
      series={[
        { name: 'Apples', color: 'indigo.6' },
        { name: 'Oranges', color: 'blue.6' },
        { name: 'Tomatoes', color: 'teal.6' },
      ]}
    />
  );
}

TITLE: Defining the useId Hook Signature - Mantine - TypeScript DESCRIPTION: This snippet provides the TypeScript function signature for the useId hook from Mantine. It accepts an optional id parameter of type string and returns a string value representing the generated or provided ID. This function is designed as a React hook and should be used within functional React components. It is required that the environment supports React hooks, and the @mantine/hooks package is available. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-id.mdx#_snippet_1

LANGUAGE: TypeScript CODE:

function useId(id: string): string;

TITLE: Demonstrating Polymorphic Component Usage with BackgroundImage in JSX DESCRIPTION: Shows how the BackgroundImage component can be used polymorphically, changing from its default div element to a button element. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/background-image.mdx#_snippet_2

LANGUAGE: JSX CODE:

<Polymorphic
  defaultElement="div"
  changeToElement="button"
  component="BackgroundImage"
/>

TITLE: Using useMouse Hook with resetOnExit - Mantine React DESCRIPTION: This code snippet demonstrates how to use the useMouse hook with the resetOnExit option. It imports the useMouse hook from @mantine/hooks and then initializes it with the resetOnExit option set to true. This will reset the mouse position to 0, 0 when the mouse leaves the element. The ref, x, and y are then destructured for usage. The target element will be whatever element you pass the ref to. Dependencies include @mantine/hooks. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-mouse.mdx#_snippet_1

LANGUAGE: TypeScript CODE:

import { useMouse } from '@mantine/hooks';

const { ref, x, y } = useMouse({ resetOnExit: true });

TITLE: Importing Mantine Dates Styles - JavaScript DESCRIPTION: This code snippet provides the necessary import statement to apply the default styles for the @mantine/dates package. Including this line, typically in your application's entry file (like main.tsx or App.tsx), resolves styling issues that cause the date components to appear broken. It is a simple CSS import presented within a markdown code block tagged as bash, showing the exact line to add. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/dates-missing-styles.mdx#_snippet_0

LANGUAGE: JavaScript CODE:

import '@mantine/dates/styles.css';

TITLE: Reinitializing useScrollSpy Hook DESCRIPTION: This code demonstrates how to use the reinitialize function of the useScrollSpy hook. It uses the useEffect hook to reinitialize the hook's data when the dependency prop changes. This allows for updating the headings data after the parent component has mounted. It requires the @mantine/hooks library. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-scroll-spy.mdx#_snippet_2

LANGUAGE: tsx CODE:

import { useEffect } from 'react';
import { useScrollSpy } from '@mantine/hooks';

function Demo({ dependency }) {
  const { reinitialize } = useScrollSpy();

  useEffect(() => {
    reinitialize();
  }, [dependency]);

  return null;
}

TITLE: Using React Nodes as Errors – Mantine DESCRIPTION: Demonstrates how to use any React node as an error message. This provides flexibility in styling and displaying error messages. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/errors.mdx#_snippet_6

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { name: '', email: '' },
  initialErrors: {
    name: <p>Paragraph error</p>, // -> error as a react element
    email: 42, // -> error as a number
  },
});

TITLE: Creating a Mantine Theme Override in TypeScript DESCRIPTION: Defines a Mantine custom theme by importing and invoking the 'createTheme' function from '@mantine/core'. This theme sets 'serif' as the global font family and enables further theme customization. The file should be saved as 'src/theme.ts'. Dependencies include '@mantine/core'. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/gatsby.mdx#_snippet_1

LANGUAGE: typescript CODE:

// src/theme.ts
import { createTheme } from '@mantine/core';

export const theme = createTheme({
  fontFamily: 'serif',
  // ... other theme override properties
});

TITLE: Define Local Font with next/font (TSX) DESCRIPTION: Defines a custom local font using the next/font/local package, specifying font file paths, weights, and styles. Exports the font object for use in themes. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/next-load-fonts.mdx#_snippet_0

LANGUAGE: tsx CODE:

import localFont from 'next/font/local';

export const roboto = localFont({
  src: [
    {
      path: './Roboto-Bold.woff2',
      weight: '700',
      style: 'normal',
    },
    {
      path: './Roboto-Heavy.woff2',
      weight: '900',
      style: 'normal',
    },
  ],
});

TITLE: Defining Styles with CSS Modules (SCSS) DESCRIPTION: Provides an example of a CSS module file written in SCSS, demonstrating class definitions, nesting (&), data attributes (&[data-collapsed]), media queries (@media), and mixins (@mixin hover). SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/styles-overview.mdx#_snippet_5

LANGUAGE: scss CODE:

// Demo.module.css

.root {
  padding-right: 100px;

  &[data-collapsed] {
    padding-right: 40px;

    & .control {
      max-width: 200px;
    }
  }
}

.control {
  background-color: var(--mantine-color-blue-1);
  color: var(--mantine-color-blue-filled);
  padding: var(--mantine-spacing-xl);
  margin-left: 40px;

  @media (max-width: $mantine-breakpoint-sm) {
    margin-left: 0;
    margin-top: var(--mantine-spacing-md);
  }

  @mixin hover {
    background-color: light-dark(
      var(--mantine-color-blue-1),
      var(--mantine-color-blue-9)
    );
  }
}

TITLE: Configuring CodeHighlight with Shiki adapter in Mantine DESCRIPTION: This TypeScript/React snippet shows how to set up the CodeHighlightAdapterProvider with the shiki adapter. It includes asynchronously loading the shiki highlighter and configuring it with desired languages and themes, then providing the adapter to the context provider wrapping the application. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/8.0.0.md#_snippet_11

LANGUAGE: tsx CODE:

import { MantineProvider } from '@mantine/core';
import { CodeHighlightAdapterProvider, createShikiAdapter } from '@mantine/code-highlight';

// Shiki requires async code to load the highlighter
async function loadShiki() {
  const { createHighlighter } = await import('shiki');
  const shiki = await createHighlighter({
    langs: ['tsx', 'scss', 'html', 'bash', 'json'],
    themes: [],
  });

  return shiki;
}

const shikiAdapter = createShikiAdapter(loadShiki);

function App() {
  return (
    <MantineProvider>
      <CodeHighlightAdapterProvider adapter={shikiAdapter}>
        {/* Your app here */}
      </CodeHighlightAdapterProvider>
    </MantineProvider>
  );
}

TITLE: Configuring CodeHighlight with Shiki Adapter (React/TypeScript) DESCRIPTION: This snippet demonstrates how to set up @mantine/code-highlight to use the Shiki syntax highlighter. It involves wrapping the application with CodeHighlightAdapterProvider and providing a createShikiAdapter instance, which asynchronously loads the Shiki highlighter with specified languages and themes. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/8-0-0.mdx#_snippet_3

LANGUAGE: tsx CODE:

import { MantineProvider } from '@mantine/core';
import { CodeHighlightAdapterProvider, createShikiAdapter } from '@mantine/code-highlight';

// Shiki requires async code to load the highlighter
async function loadShiki() {
  const { createHighlighter } = await import('shiki');
  const shiki = await createHighlighter({
    langs: ['tsx', 'scss', 'html', 'bash', 'json'],
    themes: [],
  });

  return shiki;
}

const shikiAdapter = createShikiAdapter(loadShiki);

function App() {
  return (
    <MantineProvider>
      <CodeHighlightAdapterProvider adapter={shikiAdapter}>
        {/* Your app here */}
      </CodeHighlightAdapterProvider>
    </MantineProvider>
  );
}

TITLE: Referencing Primary Color Variables in SCSS DESCRIPTION: This SCSS snippet demonstrates how to utilize Mantine's primary color CSS variables, such as --mantine-primary-color-0 for a specific shade and --mantine-primary-color-filled for background, to style elements within a stylesheet. These variables are derived from the theme.primaryColor setting. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_21

LANGUAGE: scss CODE:

.demo {
  color: var(--mantine-primary-color-0);
  background-color: var(--mantine-primary-color-filled);
}

TITLE: Referencing Z-index Variables in CSS DESCRIPTION: This CSS snippet illustrates how to directly use Mantine's predefined z-index CSS variables, such as --mantine-z-index-modal, in custom stylesheets. It shows how to calculate a z-index value relative to a base Mantine variable to ensure proper layering of elements, for example, displaying content above a modal. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_25

LANGUAGE: css CODE:

/* Display content above the modal */
.my-content {
  z-index: calc(var(--mantine-z-index-modal) + 1);
}

TITLE: Locking Scroll with RemoveScroll Component (TypeScript) DESCRIPTION: This code snippet demonstrates how to use the RemoveScroll component from the @mantine/core library to lock scrolling within a specific area of your application. It wraps the content that should have its scroll locked. The component supports all props from react-remove-scroll. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/how-to-lock-scroll.mdx#_snippet_0

LANGUAGE: TypeScript CODE:

import { RemoveScroll } from '@mantine/core';

function App() {
  return (
    <RemoveScroll>
      <div>Content</div>
    </RemoveScroll>
  );
}


TITLE: Defining Single-Shade Mantine Theme Color (tsx) DESCRIPTION: Illustrates using the colorsTuple helper function from @mantine/core to quickly generate a 10-shade array from a single color value for use in the theme.colors object. This is suitable if you do not require distinct shade variations for different component variants, hover effects, or specific light/dark mode behaviors. Requires @mantine/core. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/ten-shades-per-color.mdx#_snippet_1

LANGUAGE: tsx CODE:

import { colorsTuple, createTheme } from '@mantine/core';

const theme = createTheme({
  colors: {
    custom: colorsTuple('#FFC0CB'),
  },
});

TITLE: Initializing useListState Hook DESCRIPTION: This snippet demonstrates how to initialize the useListState hook, which is a custom hook for managing list state in React. It takes an initial array as an argument and returns an array containing the current list values and a set of handlers for manipulating the list. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-list-state.mdx#_snippet_0

LANGUAGE: tsx CODE:

import { useListState } from '@mantine/hooks';

const [values, handlers] = useListState([{ a: 1 }]);

TITLE: Adding New Custom Font Sizes to Mantine Theme (TypeScript) DESCRIPTION: This snippet demonstrates how to introduce entirely new font size variables (e.g., xxs, xxl) to the Mantine theme via theme.fontSizes. These custom sizes will be available as CSS variables in the --mantine-font-size-{size} format. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/css-variables.mdx#_snippet_8

LANGUAGE: tsx CODE:

import { createTheme } from '@mantine/core';

const theme = createTheme({
  fontSizes: {
    xxs: '0.125rem',
    xxl: '2rem',
  },
});

TITLE: Extending MantineThemeSizesOverride Interface (TSX) DESCRIPTION: This example illustrates how to extend the MantineThemeSizesOverride interface in a .d.ts file to add custom size names for theme.spacing and theme.radius. It involves importing DefaultMantineSize and defining union types for the extended sizes. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/typescript.mdx#_snippet_10

LANGUAGE: tsx CODE:

import {
  DefaultMantineSize,
  MantineThemeSizesOverride,
} from '@mantine/core';

type ExtendedCustomSpacing =
  | 'xxl'
  | 'xxxs'
  | DefaultMantineSize;

type ExtendedCustomRadius =
  | 'xxs'
  | DefaultMantineSize;

declare module '@mantine/core' {
  export interface MantineThemeSizesOverride {
    spacing: Record<ExtendedCustomSpacing, string>;
    radius: Record<ExtendedCustomRadius, string>;
  }
}

TITLE: Detecting First Render with Mantine's useIsFirstRender Hook (TSX) DESCRIPTION: Shows how to use the useIsFirstRender hook from @mantine/hooks to determine if the current render is the first mount. The component tracks a counter with useState and signals the first render status using colored text. Dependencies are React, @mantine/core, and Mantine hooks, and the display updates in response to rerender events. Suitable for conditional initialization or one-time logic. SOURCE: https://github.com/mantinedev/mantine/blob/master/changelog/7.8.0.md#_snippet_14

LANGUAGE: tsx CODE:

import { useState } from 'react';
import { Button, Text } from '@mantine/core';
import { useIsFirstRender } from '@mantine/hooks';

function Demo() {
  const [counter, setCounter] = useState(0);
  const firstRender = useIsFirstRender();
  return (
    <div>
      <Text>
        Is first render:{' '}
        <Text span c={firstRender ? 'teal' : 'red'}>
          {firstRender ? 'Yes' : 'No!'}
        </Text>
      </Text>
      <Button onClick={() => setCounter((c) => c + 1)} mt="sm">
        Rerendered {counter} times, click to rerender
      </Button>
    </div>
  );
}

TITLE: Using Mantine Styles Utilities (u) as Selectors - TSX DESCRIPTION: Provides an example of how to use the utility properties from the u object (like u.dark, u.rtl, u.smallerThan) directly as keys in a styles object to apply conditional styles based on color scheme, direction, or breakpoints. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/emotion.mdx#_snippet_16

LANGUAGE: TSX CODE:

const styles = {
  root: {
    [u.dark]: { color: 'white' },
    [u.rtl]: { padding: 10 },
    [u.smallerThan('md')]: { lineHeight: 20 },
  },
};

TITLE: Using isValid to Check Form Validation Status with Mantine useForm in TypeScript DESCRIPTION: Demonstrates usage of the isValid method which performs silent validation returning a boolean indicating overall or per-field validity without populating form errors. The form is initialized with initial values and inline validation rules. Depends on '@mantine/form'. Inputs include initialValues and field-specific validation functions; output is boolean validation results. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/validation.mdx#_snippet_6

LANGUAGE: tsx CODE:

import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { name: '', age: 0 },
  validate: {
    name: (value) => (value.trim().length < 2 ? 'Too short' : null),
    age: (value) => (value < 18 ? 'Too young' : null),
  },
});

// get validation status of all values
form.isValid(); // -> false

// get validation status of field
form.isValid('name'); // -> false

TITLE: Demonstrating Supported and Unsupported Types for useSetState (TypeScript/TSX) DESCRIPTION: This snippet demonstrates proper and improper usage of the useSetState hook, highlighting that only objects are supported as the initial state. Attempts to use arrays or primitive values as the initial state will fail, while using objects—including objects with array properties—is valid. Requires @mantine/hooks and TypeScript; input must be an object or the hook will not function. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/hooks/use-set-state.mdx#_snippet_1

LANGUAGE: TSX CODE:

import { useSetState } from '@mantine/hooks';

useSetState([1, 2, 3]); // -> will not work
useSetState(1); // -> will not work
useSetState({ skills: ['JavaScript', 'TypeScript'] }); // -> works fine

TITLE: Implementing forwardRef for proper Tooltip compatibility DESCRIPTION: This example demonstrates the correct way to create a custom component that works with Tooltip by using forwardRef to pass the ref to the root element, enabling proper positioning. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tooltip.mdx#_snippet_2

LANGUAGE: tsx CODE:

// Example of code that will work
import { forwardRef } from 'react';
import { Tooltip } from '@mantine/core';

const MyComponent = forwardRef<HTMLDivElement>((props, ref) => (
  <div ref={ref} {...props}>
    My component
  </div>
));

// Works correctly – ref is forwarded
function Demo() {
  return (
    <Tooltip label="Works fine">
      <MyComponent />
    </Tooltip>
  );
}

TITLE: Implementing Headroom Effect for AppShell Header in React (TSX) DESCRIPTION: Demonstrates how to create a header that hides on scroll down and reappears on scroll up (headroom effect) using the AppShell component. It utilizes the useHeadroom hook from @mantine/hooks to control the collapsed state of the AppShell.Header and sets header.offset to false to prevent the main content area from reserving space for the header when hidden. Manual padding-top is applied to AppShell.Main to account for the header height. Requires @mantine/core and @mantine/hooks. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/app-shell.mdx#_snippet_9

LANGUAGE: tsx CODE:

import { AppShell, rem } from '@mantine/core';
import { useHeadroom } from '@mantine/hooks';

function Demo() {
  const pinned = useHeadroom({ fixedAt: 120 });

  return (
    <AppShell
      header={{ height: 60, collapsed: !pinned, offset: false }}
      padding="md"
    >
      <AppShell.Header>Header</AppShell.Header>

      <AppShell.Main
        pt={`calc(${rem(60)} + var(--mantine-spacing-md))`}
      >
        {/* Content */}
      </AppShell.Main>
    </AppShell>
  );
}

TITLE: Resetting Touched and Dirty State in Mantine Form DESCRIPTION: This code snippet shows how to use form.resetTouched and form.resetDirty functions to clear the touched and dirty states of the form. form.reset also resets the touched and dirty state. Requires @mantine/form. SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/form/status.mdx#_snippet_3

LANGUAGE: tsx CODE:

```tsx
import { useForm } from '@mantine/form';

const form = useForm({
  mode: 'uncontrolled',
  initialValues: { a: 1 },
  initialTouched: { a: true },
  initialDirty: { a: true },
});

form.isDirty('a'); // -> true
form.isTouched('a'); // -> true

form.resetTouched();
form.isTouched('a'); // -> false

form.resetDirty();
form.isDirty('a'); // -> false

----------------------------------------

TITLE: Controlling Mantine Menu State (TSX)
DESCRIPTION: Demonstrates how to manage the opened state of the Mantine Menu component using React's useState hook and the `opened` and `onChange` props.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/menu.mdx#_snippet_0

LANGUAGE: tsx
CODE:

import { useState } from 'react'; import { Menu } from '@mantine/core';

function Demo() { const [opened, setOpened] = useState(false); return ( <Menu opened={opened} onChange={setOpened}> {/* Menu content */} </Menu> ); }


----------------------------------------

TITLE: Building a Fixed Footer Layout Using CSS
DESCRIPTION: Provides a CSS strategy to create a fixed footer on a webpage. It instructs to set the footer's CSS position to fixed with bottom zero, wrap all content except the footer in a container div, and assign min-height 100vh to this container to ensure the footer remains at the bottom. Setting a background color on the content container is necessary to prevent visual overlap. This snippet is conceptual and demonstrates layout best practices for sticky footers.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/help.mantine.dev/src/pages/q/how-that-thing-is-done.mdx#_snippet_1

LANGUAGE: CSS
CODE:

/* Footer styles */ footer { position: fixed; bottom: 0; }

/* Content container styles / .content-container { min-height: 100vh; background-color: / your background color */; }


----------------------------------------

TITLE: Implementing Gatsby Browser API Wrapper with MantineProvider in TypeScript
DESCRIPTION: Defines the 'wrapPageElement' Gatsby browser API function to wrap the root element with MantineProvider using the custom theme. It also imports Mantine's global styles for proper styling of components. This file named 'gatsby-browser.tsx' ensures Mantine styles and theming are applied during client-side navigation. Dependencies include '@mantine/core' and the local theme definition.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/gatsby.mdx#_snippet_3

LANGUAGE: typescript
CODE:

// Import styles of packages that you've installed. // All packages except @mantine/hooks require styles imports import '@mantine/core/styles.css';

import { MantineProvider } from '@mantine/core'; import { theme } from './src/theme';

export const wrapPageElement = ({ element }) => { return <MantineProvider theme={theme}>{element}</MantineProvider>; };


----------------------------------------

TITLE: Defining and Ordering CSS Layers (SCSS)
DESCRIPTION: Illustrates the use of the @layer directive to explicitly define and order CSS layers. Explains how this can be used to control the cascade order between different libraries or style types (e.g., base, mantine, components).
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/changelog/7-1-0.mdx#_snippet_2

LANGUAGE: scss
CODE:

@layer base, mantine, components;


----------------------------------------

TITLE: Use Mantine Breakpoint Variable in CSS Module (CSS)
DESCRIPTION: Illustrates how to use the static breakpoint variables defined in the PostCSS configuration within a CSS module file. This allows applying styles based on Mantine's defined breakpoints using the `$variable-name` syntax provided by `postcss-simple-vars`.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/styles/responsive.mdx#_snippet_2

LANGUAGE: css
CODE:

.demo { @media (max-width: $mantine-breakpoint-xs) { background-color: red; } }


----------------------------------------

TITLE: Select component with aria-label on clear button
DESCRIPTION: This example demonstrates how to set `aria-label` on the clear button for accessibility purposes using the `clearButtonProps` prop. This is necessary when the `clearable` prop is set.  It is important for screen readers.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/select.mdx#_snippet_3

LANGUAGE: typescript
CODE:

import { Select } from '@mantine/core';

function Demo() { return ( <Select data={[]} clearable clearButtonProps={{ 'aria-label': 'Clear input', }} /> ); }


----------------------------------------

TITLE: Defining Table Data for Mantine Table in TypeScript/React
DESCRIPTION: This snippet defines an array of element objects to provide tabular data for examples using Mantine's Table component. Each object contains the properties 'position', 'mass', 'symbol', and 'name'. The array is expected to be typed or used directly in Table demos, serving as standardized example data. No external dependencies are required beyond basic TypeScript support, and it is designed to be used as a constant source for various Table props or renderings. Input is implicit in the data definition and output is consumption by table components; there are no special constraints except TypeScript type compatibility.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/table.mdx#_snippet_0

LANGUAGE: TSX
CODE:

const elements = [ { position: 6, mass: 12.011, symbol: 'C', name: 'Carbon' }, { position: 7, mass: 14.007, symbol: 'N', name: 'Nitrogen' }, { position: 39, mass: 88.906, symbol: 'Y', name: 'Yttrium' }, { position: 56, mass: 137.33, symbol: 'Ba', name: 'Barium' }, { position: 58, mass: 140.12, symbol: 'Ce', name: 'Cerium' }, ];


----------------------------------------

TITLE: Mantine Tabs with aria-label on Tabs.List
DESCRIPTION: Demonstrates how to add `aria-label` attribute to `Tabs.List`. This attribute is used to label the list of tabs for screen readers to improve accessibility. The label will be announced when the tab list is focused for the first time.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/core/tabs.mdx#_snippet_7

LANGUAGE: typescript
CODE:

import { Tabs } from '@mantine/core';

function Demo() { return ( <Tabs defaultValue="recent"> {/* Tabs.List aria-label will be announced when tab is focused for the first time */} <Tabs.List aria-label="Chats"> <Tabs.Tab value="recent">Most recent</Tabs.Tab> <Tabs.Tab value="recent">Unanswered</Tabs.Tab> <Tabs.Tab value="archived">Archived</Tabs.Tab> </Tabs.List> </Tabs> ); }


----------------------------------------

TITLE: Migrating theme.colorScheme to CSS Modules
DESCRIPTION: Shows how to migrate from theme.colorScheme in 6.x to light-dark function or mixins in 7.x CSS.
SOURCE: https://github.com/mantinedev/mantine/blob/master/apps/mantine.dev/src/pages/guides/6x-to-7x.mdx#_snippet_10

LANGUAGE: tsx
CODE:

// 6.x import { createStyles } from '@mantine/core';

const useStyles = createStyles((theme) => ({ root: { backgroundColor: theme.colorScheme === 'dark' ? theme.colors.dark[6] : theme.colors.gray[0], color: theme.colorScheme === 'dark' ? theme.white : theme.black, }, }));


LANGUAGE: scss
CODE:

/* 7.0 */

/* With light-dark function */ .root { background-color: light-dark( var(--mantine-color-gray-0), var(--mantine-color-dark-6) ); color: light-dark( var(--mantine-color-black), var(--mantine-color-white) ); }

/* With light/dark mixins */ .root { background-color: var(--mantine-color-gray-0); color: var(--mantine-color-black);

@mixin dark { background-color: var(--mantine-color-dark-6); color: var(--mantine-color-white); } }