0
# CSS-in-JS Integration
1
2
Styled component creation, CSS utilities, and advanced styling patterns with full theme integration. This system provides powerful CSS-in-JS capabilities while maintaining theme consistency and developer experience.
3
4
## Capabilities
5
6
### Styled Component API
7
8
Create styled React components with theme integration and advanced styling capabilities.
9
10
```typescript { .api }
11
/**
12
* Main styled component API with theme integration
13
*/
14
declare const styled: CreateMUIStyled;
15
16
/**
17
* Styled component creation interface
18
*/
19
interface CreateMUIStyled {
20
/** Create styled component from HTML element */
21
<Tag extends keyof HTMLElementTagNameMap>(
22
tag: Tag
23
): StyledComponent<Tag, {}, Theme>;
24
25
/** Create styled component from React component */
26
<Component extends React.ComponentType<any>>(
27
component: Component
28
): StyledComponent<Component, {}, Theme>;
29
30
/** Create styled component with options */
31
<Tag extends keyof HTMLElementTagNameMap>(
32
tag: Tag,
33
options: StyledOptions
34
): StyledComponent<Tag, {}, Theme>;
35
36
<Component extends React.ComponentType<any>>(
37
component: Component,
38
options: StyledOptions
39
): StyledComponent<Component, {}, Theme>;
40
}
41
42
/**
43
* Styled component type
44
*/
45
interface StyledComponent<
46
Component extends React.ElementType,
47
Props = {},
48
Theme = Theme
49
> extends React.ComponentType<Props & MUIStyledCommonProps<Theme>> {
50
/** Apply additional styles */
51
<AdditionalProps = {}>(
52
styles:
53
| CSSInterpolation
54
| ((props: Props & AdditionalProps & { theme: Theme }) => CSSInterpolation)
55
): StyledComponent<Component, Props & AdditionalProps, Theme>;
56
}
57
58
/**
59
* Common props for all styled components
60
*/
61
interface MUIStyledCommonProps<Theme = Theme> {
62
/** Advanced styling with theme access */
63
sx?: SxProps<Theme>;
64
65
/** CSS class name */
66
className?: string;
67
68
/** All system props */
69
[key: string]: any;
70
}
71
72
/**
73
* Styling options for styled components
74
*/
75
interface StyledOptions {
76
/** Display name for debugging */
77
name?: string;
78
79
/** Component identifier */
80
slot?: string;
81
82
/** Skip theme integration */
83
skipTheme?: boolean;
84
85
/** Skip sx prop processing */
86
skipSx?: boolean;
87
88
/** Custom prop filtering */
89
shouldForwardProp?: (prop: string) => boolean;
90
}
91
92
/**
93
* Utility function for prop filtering
94
* @param prop - Prop name to check
95
* @returns True if prop should be forwarded to DOM
96
*/
97
function shouldForwardProp(prop: string): boolean;
98
```
99
100
**Usage Examples:**
101
102
```typescript
103
import { styled } from "@mui/system";
104
105
// Basic styled component
106
const StyledButton = styled('button')({
107
backgroundColor: 'blue',
108
color: 'white',
109
padding: '8px 16px',
110
border: 'none',
111
borderRadius: '4px',
112
});
113
114
// Styled component with theme access
115
const ThemedBox = styled('div')(({ theme }) => ({
116
backgroundColor: theme.palette.primary.main,
117
padding: theme.spacing(2),
118
[theme.breakpoints.up('md')]: {
119
padding: theme.spacing(3),
120
},
121
}));
122
123
// Styled component with props
124
const FlexContainer = styled('div')<{ direction?: 'row' | 'column' }>(
125
({ theme, direction = 'row' }) => ({
126
display: 'flex',
127
flexDirection: direction,
128
gap: theme.spacing(1),
129
})
130
);
131
132
// Using with existing component
133
import { Box } from "@mui/system";
134
135
const StyledBox = styled(Box)(({ theme }) => ({
136
backgroundColor: theme.palette.background.paper,
137
borderRadius: theme.shape.borderRadius,
138
}));
139
140
// With styling options
141
const CustomComponent = styled('div', {
142
name: 'MyCustomComponent',
143
slot: 'Root',
144
shouldForwardProp: (prop) => prop !== 'customProp',
145
})<{ customProp?: boolean }>(({ theme, customProp }) => ({
146
color: customProp ? theme.palette.primary.main : theme.palette.text.primary,
147
}));
148
```
149
150
### Styled Component Factory
151
152
Create custom styled functions with specific theme types and configurations.
153
154
```typescript { .api }
155
/**
156
* Factory for creating custom styled functions
157
* @param options - Styled creation options
158
* @returns Custom styled function
159
*/
160
function createStyled<Theme extends object = Theme>(
161
options?: StyledEngineOptions<Theme>
162
): CreateMUIStyled<Theme>;
163
164
interface StyledEngineOptions<Theme> {
165
/** Default theme object */
166
defaultTheme?: Theme;
167
168
/** Theme identifier */
169
themeId?: string;
170
171
/** Root CSS class */
172
rootShouldForwardProp?: (prop: string) => boolean;
173
}
174
175
/**
176
* Custom styled function with specific theme
177
*/
178
interface CreateMUIStyled<Theme = Theme> {
179
<Tag extends keyof HTMLElementTagNameMap>(
180
tag: Tag
181
): StyledComponent<Tag, {}, Theme>;
182
183
<Component extends React.ComponentType<any>>(
184
component: Component
185
): StyledComponent<Component, {}, Theme>;
186
}
187
```
188
189
**Usage Examples:**
190
191
```typescript
192
import { createStyled } from "@mui/system";
193
194
// Custom theme type
195
interface CustomTheme {
196
colors: {
197
primary: string;
198
secondary: string;
199
};
200
spacing: (value: number) => string;
201
}
202
203
// Create styled function with custom theme
204
const customStyled = createStyled<CustomTheme>({
205
defaultTheme: {
206
colors: {
207
primary: '#1976d2',
208
secondary: '#dc004e',
209
},
210
spacing: (value) => `${value * 8}px`,
211
},
212
});
213
214
// Use custom styled function
215
const CustomButton = customStyled('button')(({ theme }) => ({
216
backgroundColor: theme.colors.primary,
217
padding: theme.spacing(1),
218
}));
219
```
220
221
### CSS Utilities (Re-exported)
222
223
Core CSS-in-JS utilities from the styled engine for advanced styling patterns.
224
225
```typescript { .api }
226
/**
227
* CSS template literal function for writing CSS
228
* @param template - Template string array
229
* @param interpolations - CSS interpolations
230
* @returns CSS interpolation object
231
*/
232
function css(
233
template: TemplateStringsArray,
234
...interpolations: CSSInterpolation[]
235
): CSSInterpolation;
236
237
/**
238
* CSS keyframes function for animations
239
* @param template - Template string array
240
* @param interpolations - CSS interpolations
241
* @returns Keyframes object
242
*/
243
function keyframes(
244
template: TemplateStringsArray,
245
...interpolations: CSSInterpolation[]
246
): Keyframes;
247
248
/**
249
* CSS interpolation types
250
*/
251
type CSSInterpolation =
252
| CSSObject
253
| string
254
| number
255
| false
256
| null
257
| undefined
258
| CSSInterpolation[];
259
260
/**
261
* CSS object type
262
*/
263
interface CSSObject {
264
[property: string]:
265
| string
266
| number
267
| CSSObject
268
| undefined
269
| null;
270
}
271
272
/**
273
* Keyframes type for animations
274
*/
275
interface Keyframes {
276
name: string;
277
styles: string;
278
}
279
```
280
281
**Usage Examples:**
282
283
```typescript
284
import { css, keyframes, styled } from "@mui/system";
285
286
// Using css function
287
const baseStyles = css`
288
display: flex;
289
align-items: center;
290
padding: 16px;
291
`;
292
293
// Creating keyframes
294
const fadeIn = keyframes`
295
from {
296
opacity: 0;
297
transform: translateY(-10px);
298
}
299
to {
300
opacity: 1;
301
transform: translateY(0);
302
}
303
`;
304
305
// Using in styled component
306
const AnimatedBox = styled('div')`
307
${baseStyles}
308
animation: ${fadeIn} 0.3s ease-in-out;
309
`;
310
311
// Mixed object and template literal styles
312
const MixedStyledComponent = styled('div')(
313
({ theme }) => ({
314
backgroundColor: theme.palette.background.paper,
315
}),
316
css`
317
border-radius: 4px;
318
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
319
`
320
);
321
```
322
323
### Styling Engine Provider
324
325
Configure the CSS-in-JS engine (emotion or styled-components) for the entire application.
326
327
```typescript { .api }
328
/**
329
* Provider for configuring the styling engine
330
*/
331
declare const StyledEngineProvider: React.ComponentType<StyledEngineProviderProps>;
332
333
interface StyledEngineProviderProps {
334
/** Child components */
335
children: React.ReactNode;
336
337
/** Styled engine instance */
338
injectFirst?: boolean;
339
340
/** Cache configuration (emotion-specific) */
341
cache?: any;
342
}
343
```
344
345
**Usage Examples:**
346
347
```typescript
348
import { StyledEngineProvider } from "@mui/system";
349
import { CacheProvider } from "@emotion/react";
350
import createCache from "@emotion/cache";
351
352
// Emotion cache configuration
353
const cache = createCache({
354
key: 'mui',
355
prepend: true,
356
});
357
358
function App() {
359
return (
360
<StyledEngineProvider injectFirst>
361
<CacheProvider value={cache}>
362
{/* Your app components */}
363
</CacheProvider>
364
</StyledEngineProvider>
365
);
366
}
367
```
368
369
### Global Styles
370
371
Inject global CSS styles into the document with theme integration.
372
373
```typescript { .api }
374
/**
375
* Component for injecting global CSS styles
376
*/
377
declare const GlobalStyles: React.ComponentType<GlobalStylesProps>;
378
379
interface GlobalStylesProps<Theme = Theme> {
380
/** Global styles to inject */
381
styles:
382
| CSSInterpolation
383
| ((theme: Theme) => CSSInterpolation);
384
385
/** Default theme if no ThemeProvider */
386
defaultTheme?: Theme;
387
388
/** Theme identifier */
389
themeId?: string;
390
}
391
```
392
393
**Usage Examples:**
394
395
```typescript
396
import { GlobalStyles, createTheme, ThemeProvider } from "@mui/system";
397
398
const theme = createTheme();
399
400
// Basic global styles
401
<GlobalStyles
402
styles={{
403
body: {
404
margin: 0,
405
fontFamily: 'Roboto, sans-serif',
406
},
407
}}
408
/>
409
410
// Global styles with theme access
411
<ThemeProvider theme={theme}>
412
<GlobalStyles
413
styles={(theme) => ({
414
'*': {
415
boxSizing: 'border-box',
416
},
417
body: {
418
margin: 0,
419
backgroundColor: theme.palette.background.default,
420
color: theme.palette.text.primary,
421
},
422
'#root': {
423
minHeight: '100vh',
424
},
425
})}
426
/>
427
</ThemeProvider>
428
429
// CSS template literal global styles
430
<GlobalStyles
431
styles={css`
432
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
433
434
html {
435
font-size: 16px;
436
line-height: 1.5;
437
}
438
439
* {
440
box-sizing: border-box;
441
}
442
`}
443
/>
444
```
445
446
### Component Factory Functions
447
448
Factory functions for creating custom components with built-in system props and theme integration.
449
450
```typescript { .api }
451
/**
452
* Create custom Box component with theme integration
453
* @param options - Box creation options
454
* @returns Custom Box component
455
*/
456
function createBox<Theme extends object = Theme>(
457
options?: CreateBoxOptions<Theme>
458
): React.ComponentType<BoxProps<Theme>>;
459
460
interface CreateBoxOptions<Theme = Theme> {
461
/** Theme identifier for accessing nested themes */
462
themeId?: string;
463
464
/** Default theme if no ThemeProvider exists */
465
defaultTheme?: Theme;
466
467
/** Default CSS class name */
468
defaultClassName?: string;
469
470
/** Custom class name generation function */
471
generateClassName?: (className: string) => string;
472
}
473
474
/**
475
* Create custom Container component with responsive behavior
476
* @param options - Container creation options
477
* @returns Custom Container component
478
*/
479
function createContainer<Theme extends object = Theme>(
480
options?: CreateContainerOptions<Theme>
481
): React.ComponentType<ContainerProps<Theme>>;
482
483
interface CreateContainerOptions<Theme = Theme> {
484
/** Theme identifier for accessing nested themes */
485
themeId?: string;
486
487
/** Default theme if no ThemeProvider exists */
488
defaultTheme?: Theme;
489
490
/** Default CSS class name */
491
defaultClassName?: string;
492
493
/** Custom class name generation function */
494
generateClassName?: (className: string) => string;
495
496
/** Default maximum width breakpoints */
497
defaultMaxWidths?: Record<string, string | number>;
498
499
/** Whether to disable gutters by default */
500
defaultDisableGutters?: boolean;
501
}
502
503
/**
504
* Create custom styled engine with specific configuration
505
* @param options - Styled engine options
506
* @returns Custom styled function
507
*/
508
function createStyled<Theme extends object = Theme>(
509
options?: StyledOptions<Theme>
510
): CreateMUIStyled<Theme>;
511
512
interface StyledOptions<Theme = Theme> {
513
/** Default theme */
514
defaultTheme?: Theme;
515
516
/** Theme identifier */
517
themeId?: string;
518
519
/** Root CSS class selector */
520
rootShouldForwardProp?: (prop: string) => boolean;
521
522
/** Product name for class generation */
523
productionPrefix?: string[];
524
}
525
526
// Component props interfaces
527
interface BoxProps<Theme = Theme> extends SystemProps<Theme> {
528
children?: React.ReactNode;
529
component?: React.ElementType;
530
sx?: SxProps<Theme>;
531
}
532
533
interface ContainerProps<Theme = Theme> {
534
children?: React.ReactNode;
535
maxWidth?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | false;
536
fixed?: boolean;
537
disableGutters?: boolean;
538
component?: React.ElementType;
539
sx?: SxProps<Theme>;
540
}
541
```
542
543
**Usage Examples:**
544
545
```typescript
546
import { createBox, createContainer, createStyled } from "@mui/system";
547
548
// Create custom Box component
549
const CustomBox = createBox({
550
defaultClassName: 'MyBox-root',
551
generateClassName: (className) => `custom-${className}`,
552
});
553
554
// Create themed Container component
555
const ThemedContainer = createContainer({
556
themeId: 'custom',
557
defaultMaxWidths: {
558
xs: '100%',
559
sm: '540px',
560
md: '720px',
561
lg: '960px',
562
xl: '1140px',
563
},
564
});
565
566
// Create custom styled function
567
const myStyled = createStyled({
568
productionPrefix: ['my', 'app'],
569
rootShouldForwardProp: (prop) => prop !== 'variant',
570
});
571
572
// Using the custom factories
573
function MyComponent() {
574
return (
575
<ThemedContainer maxWidth="lg">
576
<CustomBox
577
sx={{
578
p: 2,
579
bgcolor: 'primary.main',
580
color: 'primary.contrastText',
581
}}
582
>
583
Custom themed components
584
</CustomBox>
585
</ThemedContainer>
586
);
587
}
588
589
// Styled component with custom factory
590
const StyledButton = myStyled('button')(({ theme, variant }) => ({
591
padding: theme.spacing(1, 2),
592
borderRadius: theme.shape.borderRadius,
593
backgroundColor: variant === 'primary' ? theme.palette.primary.main : 'transparent',
594
color: variant === 'primary' ? theme.palette.primary.contrastText : theme.palette.text.primary,
595
border: variant === 'outlined' ? `1px solid ${theme.palette.divider}` : 'none',
596
'&:hover': {
597
opacity: 0.8,
598
},
599
}));
600
```
601
602
### Advanced Styling Patterns
603
604
Advanced patterns for complex styling scenarios and optimizations.
605
606
```typescript { .api }
607
/**
608
* sx prop processor function (internal)
609
*/
610
function unstable_styleFunctionSx(props: {
611
sx: SxProps;
612
theme: Theme;
613
}): CSSObject;
614
615
/**
616
* Create custom sx processor
617
* @param config - sx configuration
618
* @returns Custom sx processor function
619
*/
620
function unstable_createStyleFunctionSx(
621
config?: SxConfig
622
): typeof unstable_styleFunctionSx;
623
624
/**
625
* Extend sx prop functionality
626
* @param sxProp - Original sx prop
627
* @param extensions - Additional sx properties
628
* @returns Extended sx prop
629
*/
630
function unstable_extendSxProp(
631
sxProp: SxProps,
632
extensions: SxProps
633
): SxProps;
634
635
/**
636
* Default sx configuration
637
*/
638
const unstable_defaultSxConfig: SxConfig;
639
640
/**
641
* sx prop configuration interface
642
*/
643
interface SxConfig {
644
[property: string]: {
645
cssProperty?: string | string[];
646
themeKey?: string;
647
transform?: TransformFunction;
648
style?: StyleFunction<any>;
649
};
650
}
651
```
652
653
### Component Box Creation
654
655
Create custom Box-like components with system props support.
656
657
```typescript { .api }
658
/**
659
* Create custom Box component
660
* @param options - Box creation options
661
* @returns Custom Box component
662
*/
663
function createBox<Theme extends object = Theme>(
664
options?: CreateBoxOptions<Theme>
665
): React.ComponentType<BoxProps>;
666
667
interface CreateBoxOptions<Theme> {
668
/** Default theme */
669
defaultTheme?: Theme;
670
671
/** Component class name */
672
defaultClassName?: string;
673
674
/** Theme identifier */
675
themeId?: string;
676
}
677
678
/**
679
* Default Box component with system props
680
*/
681
declare const Box: React.ComponentType<BoxProps>;
682
```
683
684
**Usage Examples:**
685
686
```typescript
687
import { createBox } from "@mui/system";
688
689
// Custom Box with specific theme
690
const CustomBox = createBox({
691
defaultTheme: customTheme,
692
defaultClassName: 'MyCustomBox',
693
});
694
695
// Usage
696
<CustomBox
697
p={2}
698
bgcolor="primary.main"
699
sx={{
700
borderRadius: 1,
701
'&:hover': {
702
transform: 'scale(1.05)',
703
},
704
}}
705
>
706
Custom box content
707
</CustomBox>
708
```
709
710
## Integration Patterns
711
712
CSS-in-JS integration works seamlessly with:
713
714
- **Theme System**: Automatic theme access in all styled components
715
- **System Props**: Full system props support in styled components
716
- **sx Prop**: Advanced styling capabilities with theme integration
717
- **Responsive Design**: Breakpoint-aware styling in all CSS-in-JS patterns
718
- **TypeScript**: Complete type safety for styled components and CSS properties
719
- **Performance**: Optimized CSS generation and caching strategies