0
# Core Components
1
2
Foundation components including Box, factory system, and essential utilities that power the entire Mantine library. These components provide the base functionality and consistent API patterns used across all other components.
3
4
## Capabilities
5
6
### Box Component
7
8
The polymorphic base component that provides foundation for all Mantine components. Box supports style props, responsive design, and serves as the building block for the entire component system.
9
10
```typescript { .api }
11
/**
12
* Polymorphic base component that provides foundation for all Mantine components
13
* Supports all HTML elements and custom components through polymorphic props
14
*/
15
function Box<C = 'div'>(props: BoxProps<C>): JSX.Element;
16
17
interface BoxProps<C = 'div'> extends MantineStyleProps {
18
/** Component to render, div by default */
19
component?: C;
20
/** Class added to the root element */
21
className?: string;
22
/** Inline style added to root component element, can subscribe to theme */
23
style?: MantineStyleProp;
24
/** CSS variables defined on root component element */
25
__vars?: CssVarsProp;
26
/** Size property passed down the HTML element */
27
__size?: string;
28
/** Breakpoint above which the component is hidden with display: none */
29
hiddenFrom?: MantineBreakpoint;
30
/** Breakpoint below which the component is hidden with display: none */
31
visibleFrom?: MantineBreakpoint;
32
/** Determines whether component should be hidden in light color scheme */
33
lightHidden?: boolean;
34
/** Determines whether component should be hidden in dark color scheme */
35
darkHidden?: boolean;
36
/** Element modifiers transformed into data- attributes */
37
mod?: BoxMod;
38
/** Children elements */
39
children?: React.ReactNode;
40
}
41
42
type BoxMod = Record<string, any> | string | (Record<string, any> | string)[];
43
44
type ElementProps<C extends React.ElementType> = React.ComponentPropsWithoutRef<C>;
45
46
type BoxComponentProps<C extends React.ElementType> = Omit<ElementProps<C>, keyof BoxProps> &
47
BoxProps<C> & {
48
component?: C;
49
};
50
```
51
52
**Basic Usage:**
53
54
```typescript
55
import { Box } from "@mantine/core";
56
57
// Basic div
58
<Box>Content</Box>
59
60
// Custom component
61
<Box component="button">Button content</Box>
62
63
// With style props
64
<Box
65
p="md"
66
m="lg"
67
bg="blue.1"
68
c="blue.9"
69
bdrs="sm"
70
>
71
Styled box
72
</Box>
73
74
// Responsive design
75
<Box
76
p={{ base: 'md', sm: 'lg', md: 'xl' }}
77
hiddenFrom="md"
78
>
79
Responsive box
80
</Box>
81
```
82
83
**Advanced Usage:**
84
85
```typescript
86
// Polymorphic with TypeScript
87
<Box<'button'>
88
component="button"
89
onClick={(event) => console.log(event)} // Fully typed
90
disabled={false} // Button-specific props
91
>
92
Typed button
93
</Box>
94
95
// With modifiers
96
<Box
97
mod={{
98
'data-active': isActive,
99
'data-size': 'large'
100
}}
101
>
102
Box with data attributes
103
</Box>
104
```
105
106
### Mantine Style Props
107
108
Comprehensive system of style props that work consistently across all components, providing responsive design and theme integration.
109
110
```typescript { .api }
111
interface MantineStyleProps {
112
/** Margin props */
113
m?: StyleProp<MantineSpacing>; // margin
114
my?: StyleProp<MantineSpacing>; // margin-block
115
mx?: StyleProp<MantineSpacing>; // margin-inline
116
mt?: StyleProp<MantineSpacing>; // margin-top
117
mb?: StyleProp<MantineSpacing>; // margin-bottom
118
ms?: StyleProp<MantineSpacing>; // margin-inline-start
119
me?: StyleProp<MantineSpacing>; // margin-inline-end
120
ml?: StyleProp<MantineSpacing>; // margin-left
121
mr?: StyleProp<MantineSpacing>; // margin-right
122
123
/** Padding props */
124
p?: StyleProp<MantineSpacing>; // padding
125
py?: StyleProp<MantineSpacing>; // padding-block
126
px?: StyleProp<MantineSpacing>; // padding-inline
127
pt?: StyleProp<MantineSpacing>; // padding-top
128
pb?: StyleProp<MantineSpacing>; // padding-bottom
129
ps?: StyleProp<MantineSpacing>; // padding-inline-start
130
pe?: StyleProp<MantineSpacing>; // padding-inline-end
131
pl?: StyleProp<MantineSpacing>; // padding-left
132
pr?: StyleProp<MantineSpacing>; // padding-right
133
134
/** Visual props */
135
bd?: StyleProp<React.CSSProperties['border']>; // border
136
bdrs?: StyleProp<MantineSpacing>; // border-radius
137
bg?: StyleProp<MantineColor>; // background
138
c?: StyleProp<MantineColor>; // color
139
opacity?: StyleProp<React.CSSProperties['opacity']>;
140
141
/** Typography props */
142
ff?: StyleProp<'monospace' | 'text' | 'heading' | string>; // font-family
143
fz?: StyleProp<MantineFontSize | `h${1|2|3|4|5|6}` | number | string>; // font-size
144
fw?: StyleProp<React.CSSProperties['fontWeight']>; // font-weight
145
lts?: StyleProp<React.CSSProperties['letterSpacing']>; // letter-spacing
146
ta?: StyleProp<React.CSSProperties['textAlign']>; // text-align
147
lh?: StyleProp<MantineLineHeight | `h${1|2|3|4|5|6}` | number | string>; // line-height
148
fs?: StyleProp<React.CSSProperties['fontStyle']>; // font-style
149
tt?: StyleProp<React.CSSProperties['textTransform']>; // text-transform
150
td?: StyleProp<React.CSSProperties['textDecoration']>; // text-decoration
151
152
/** Size props */
153
w?: StyleProp<React.CSSProperties['width']>; // width
154
miw?: StyleProp<React.CSSProperties['minWidth']>; // min-width
155
maw?: StyleProp<React.CSSProperties['maxWidth']>; // max-width
156
h?: StyleProp<React.CSSProperties['height']>; // height
157
mih?: StyleProp<React.CSSProperties['minHeight']>; // min-height
158
mah?: StyleProp<React.CSSProperties['maxHeight']>; // max-height
159
160
/** Background props */
161
bgsz?: StyleProp<React.CSSProperties['backgroundSize']>; // background-size
162
bgp?: StyleProp<React.CSSProperties['backgroundPosition']>; // background-position
163
bgr?: StyleProp<React.CSSProperties['backgroundRepeat']>; // background-repeat
164
bga?: StyleProp<React.CSSProperties['backgroundAttachment']>; // background-attachment
165
166
/** Position props */
167
pos?: StyleProp<React.CSSProperties['position']>; // position
168
top?: StyleProp<React.CSSProperties['top']>;
169
left?: StyleProp<React.CSSProperties['left']>;
170
bottom?: StyleProp<React.CSSProperties['bottom']>;
171
right?: StyleProp<React.CSSProperties['right']>;
172
inset?: StyleProp<React.CSSProperties['inset']>;
173
z?: StyleProp<React.CSSProperties['zIndex']>; // z-index
174
175
/** Display and layout props */
176
display?: StyleProp<React.CSSProperties['display']>;
177
}
178
179
type StyleProp<Value> = Value | Partial<Record<MantineBreakpoint | string, Value>>;
180
```
181
182
**Style Props Usage:**
183
184
```typescript
185
// Basic style props
186
<Box m="md" p="lg" bg="blue.1" c="dark.9" bdrs="sm">
187
Basic styling
188
</Box>
189
190
// Responsive style props
191
<Box
192
p={{ base: 'xs', sm: 'md', lg: 'xl' }}
193
fz={{ base: 'sm', md: 'lg' }}
194
ta={{ base: 'center', lg: 'left' }}
195
>
196
Responsive styling
197
</Box>
198
199
// Typography style props
200
<Box
201
ff="monospace"
202
fz="lg"
203
fw={700}
204
lh="1.4"
205
tt="uppercase"
206
td="underline"
207
>
208
Typography styling
209
</Box>
210
211
// Layout style props
212
<Box
213
w="100%"
214
maw={400}
215
h={200}
216
pos="relative"
217
display="flex"
218
>
219
Layout styling
220
</Box>
221
```
222
223
### Factory System
224
225
Component factory system that creates Mantine-compatible components with consistent API, polymorphic props, and styling capabilities.
226
227
```typescript { .api }
228
/**
229
* Creates Mantine-compatible components with consistent API and styling
230
* @param ui - Component render function
231
* @returns Factory component with Mantine features
232
*/
233
function factory<Payload extends FactoryPayload>(
234
ui: React.ForwardRefRenderFunction<Payload['ref'], Payload['props']>
235
): MantineComponent<Payload>;
236
237
interface FactoryPayload {
238
props: Record<string, any>;
239
ctx?: any;
240
ref?: any;
241
stylesNames?: string;
242
vars?: any;
243
variant?: string;
244
staticComponents?: Record<string, any>;
245
compound?: boolean;
246
}
247
248
/**
249
* Polymorphic factory for components that need to render as different elements
250
*/
251
function polymorphicFactory<Payload extends FactoryPayload>(
252
ui: React.ForwardRefRenderFunction<Payload['ref'], Payload['props']>
253
): PolymorphicFactory<Payload>;
254
255
/**
256
* Creates polymorphic component from regular component
257
* @param component - Component to make polymorphic
258
* @returns Polymorphic component
259
*/
260
function createPolymorphicComponent<T extends React.ComponentType<any>>(
261
component: T
262
): PolymorphicComponent<T>;
263
264
/**
265
* Extends component with additional props
266
* @param Component - Component to extend
267
* @returns Function to create extended component
268
*/
269
function getWithProps<T, Props>(Component: T): (props: Partial<Props>) => T;
270
271
interface MantineComponent<Payload extends FactoryPayload>
272
extends React.ForwardRefExoticComponent<Payload['props']> {
273
/** Extend component with theme configuration */
274
extend: (input: ExtendComponent<Payload>) => MantineThemeComponent;
275
/** Create component with fixed props */
276
withProps: (props: Partial<Payload['props']>) => MantineComponent<Payload>;
277
/** Component CSS classes */
278
classes?: Record<string, string>;
279
}
280
```
281
282
**Factory Usage Examples:**
283
284
```typescript
285
import { factory, Box, useStyles } from "@mantine/core";
286
287
// Basic factory component
288
interface MyButtonProps {
289
children: React.ReactNode;
290
variant?: 'primary' | 'secondary';
291
size?: 'sm' | 'md' | 'lg';
292
}
293
294
const MyButton = factory<{
295
props: MyButtonProps;
296
ref: HTMLButtonElement;
297
stylesNames: 'root' | 'label';
298
}>((props, ref) => {
299
const { children, variant = 'primary', size = 'md', ...others } = props;
300
301
return (
302
<Box
303
component="button"
304
ref={ref}
305
data-variant={variant}
306
data-size={size}
307
{...others}
308
>
309
{children}
310
</Box>
311
);
312
});
313
314
// Polymorphic factory component
315
const MyContainer = polymorphicFactory<{
316
props: { padding?: MantineSpacing };
317
ref: HTMLElement;
318
}>((props, ref) => {
319
const { padding = 'md', ...others } = props;
320
return <Box ref={ref} p={padding} {...others} />;
321
});
322
323
// Usage
324
<MyContainer component="section" padding="lg">
325
Container content
326
</MyContainer>
327
328
// Extended component with fixed props
329
const PrimaryButton = MyButton.withProps({ variant: 'primary' });
330
331
<PrimaryButton size="lg">Primary Button</PrimaryButton>
332
```
333
334
### Utility Functions
335
336
Essential utility functions used throughout the Mantine ecosystem for common operations, type safety, and component functionality.
337
338
```typescript { .api }
339
/** Object manipulation utilities */
340
function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T;
341
function keys<T extends Record<string, any>>(obj: T): (keyof T)[];
342
function filterProps<T extends Record<string, any>>(
343
props: T,
344
propsToFilter: string[]
345
): Partial<T>;
346
347
/** String utilities */
348
function camelToKebabCase(str: string): string;
349
function getSafeId(id?: string): string;
350
351
/** Unit conversion utilities */
352
function rem(value: number): string;
353
function em(value: number): string;
354
function px(value: number | string): string;
355
356
/** Number utilities */
357
function isNumberLike(value: any): boolean;
358
function findClosestNumber(value: number, numbers: number[]): number;
359
360
/** Size and theme utilities */
361
function getSize(
362
size: MantineSize | number | string | undefined,
363
sizes: Record<MantineSize, string>
364
): string | undefined;
365
function getSpacing(spacing: MantineSpacing | undefined): string | undefined;
366
function getRadius(radius: MantineRadius | undefined): string | undefined;
367
function getFontSize(fontSize: MantineFontSize | undefined): string | undefined;
368
function getLineHeight(lineHeight: MantineLineHeight | undefined): string | undefined;
369
function getShadow(shadow: MantineShadow | undefined): string | undefined;
370
371
/** Breakpoint utilities */
372
function getBreakpointValue(
373
breakpoint: MantineBreakpoint | number,
374
theme: MantineTheme
375
): number;
376
function getSortedBreakpoints(theme: MantineTheme): Array<[string, number]>;
377
function getBaseValue<T>(value: T | Record<string, T>): T;
378
379
/** Context utilities */
380
function createSafeContext<T>(errorMessage: string): [
381
React.Provider<T>,
382
() => T,
383
React.Context<T | null>
384
];
385
function createOptionalContext<T>(defaultValue?: T): [
386
React.Provider<T>,
387
() => T | undefined
388
];
389
390
/** Event utilities */
391
function createEventHandler<T extends (...args: any[]) => any>(
392
outsideHandler?: T,
393
thisHandler?: T
394
): T;
395
function createScopedKeydownHandler(
396
handlers: Record<string, (event: KeyboardEvent) => void>
397
): (event: KeyboardEvent) => void;
398
function closeOnEscape(callback: () => void, options?: { active?: boolean }): (event: KeyboardEvent) => void;
399
400
/** Element utilities */
401
function isElement(value: any): value is React.ReactElement;
402
function findElementAncestor(
403
element: HTMLElement,
404
selector: string
405
): HTMLElement | null;
406
function getDefaultZIndex(level: 'app' | 'modal' | 'popover' | 'overlay' | 'max'): number;
407
408
/** Performance utilities */
409
function memoize<T extends (...args: any[]) => any>(fn: T): T;
410
function noop(): void;
411
412
/** Environment utilities */
413
function getEnv(): {
414
NODE_ENV: string;
415
MANTINE_DEV_MODE: boolean;
416
};
417
418
/** Hook utilities */
419
function useHovered(): { hovered: boolean; ref: React.RefObject<HTMLElement> };
420
function createUseExternalEvents<T extends Record<string, Function>>(
421
events: T
422
): () => T;
423
```
424
425
**Utility Usage Examples:**
426
427
```typescript
428
import {
429
rem, px, deepMerge, getSize, createSafeContext,
430
closeOnEscape, isNumberLike
431
} from "@mantine/core";
432
433
// Unit conversion
434
const spacing = rem(16); // '1rem'
435
const pixels = px('1rem'); // '16px'
436
437
// Object utilities
438
const merged = deepMerge(
439
{ a: 1, b: { c: 2 } },
440
{ b: { d: 3 } }
441
); // { a: 1, b: { c: 2, d: 3 } }
442
443
// Size utilities with theme
444
const buttonHeight = getSize('md', theme.spacing); // Gets 'md' value from theme
445
446
// Context creation
447
const [Provider, useContext] = createSafeContext<MyContextType>(
448
'useMyContext must be used within MyProvider'
449
);
450
451
// Event handling
452
useEffect(() => {
453
const handleEscape = closeOnEscape(() => setOpen(false));
454
document.addEventListener('keydown', handleEscape);
455
return () => document.removeEventListener('keydown', handleEscape);
456
}, []);
457
458
// Type checking
459
if (isNumberLike(value)) {
460
// value can be converted to number
461
const num = Number(value);
462
}
463
```
464
465
### InlineStyles Component
466
467
Component for injecting inline CSS styles into the document, useful for dynamic styling and CSS variable management.
468
469
```typescript { .api }
470
/**
471
* Component for injecting inline CSS styles into the document
472
* @param props - InlineStyles props
473
*/
474
function InlineStyles(props: InlineStylesProps): JSX.Element;
475
476
interface InlineStylesProps {
477
/** CSS styles to inject */
478
styles: string | Record<string, any>;
479
/** Nonce attribute for CSP */
480
nonce?: string;
481
}
482
```
483
484
**Usage Examples:**
485
486
```typescript
487
import { InlineStyles } from "@mantine/core";
488
489
// Inject CSS string
490
<InlineStyles styles={`
491
.custom-class {
492
color: red;
493
font-weight: bold;
494
}
495
`} />
496
497
// Inject CSS object
498
<InlineStyles
499
styles={{
500
'.my-component': {
501
backgroundColor: 'blue',
502
padding: '1rem'
503
}
504
}}
505
/>
506
507
// With CSP nonce
508
<InlineStyles
509
styles="/* CSS content */"
510
nonce={getNonce()}
511
/>
512
```
513
514
### Random Class Name Utilities
515
516
Utilities for generating unique class names to avoid style conflicts and enable style isolation.
517
518
```typescript { .api }
519
/**
520
* Hook to generate random class name for style isolation
521
* @returns Random class name string
522
*/
523
function useRandomClassName(): string;
524
525
/**
526
* Generate style object from Box style props
527
* @param styleProps - Style properties
528
* @param theme - Mantine theme
529
* @returns CSS style object
530
*/
531
function getStyleObject(
532
styleProps: MantineStyleProps,
533
theme: MantineTheme
534
): React.CSSProperties;
535
```
536
537
**Usage:**
538
539
```typescript
540
import { useRandomClassName, getStyleObject, useMantineTheme } from "@mantine/core";
541
542
function MyComponent({ m, p, bg, ...styleProps }) {
543
const className = useRandomClassName();
544
const theme = useMantineTheme();
545
const styles = getStyleObject({ m, p, bg, ...styleProps }, theme);
546
547
return (
548
<div className={className} style={styles}>
549
Isolated component
550
</div>
551
);
552
}
553
```