### Framework Example: Create React App Setup
Source: https://v6.mui.com/material-ui/experimental-api/classname-generator
Demonstrates importing the ClassNameGenerator setup file in a Create React App application.
```javascript
+import './MuiClassNameSetup';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render();
```
--------------------------------
### Framework Example: Next.js Pages Router Setup
Source: https://v6.mui.com/material-ui/experimental-api/classname-generator
Shows how to import the ClassNameGenerator setup file in a Next.js application using the Pages Router.
```javascript
+import './MuiClassNameSetup';
import * as React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
export default function MyApp(props) {
const { Component, pageProps } = props;
return (
);
}
```
--------------------------------
### Importing Setup in App
Source: https://v6.mui.com/material-ui/experimental-api/classname-generator
Example of importing the ClassNameSetup file in the root of an application before other Material UI component imports.
```javascript
import './MuiClassNameSetup';
import Button from '@mui/material/Button';
// ...other component imports
function App() {
return ;
}
```
--------------------------------
### Manual installation for Next.js
Source: https://v6.mui.com/material-ui/experimental-api/pigment-css
Install the required Pigment CSS packages for a Next.js project.
```bash
npm install @pigment-css/react
npm install --save-dev @pigment-css/nextjs-plugin
```
--------------------------------
### Install RTL plugin
Source: https://v6.mui.com/material-ui/customization/right-to-left
Installs the necessary dependencies for RTL support.
```bash
npm install stylis stylis-plugin-rtl
```
--------------------------------
### Install Material Icons
Source: https://v6.mui.com/material-ui/getting-started/installation
Installs the Material Icons package.
```bash
npm install @mui/icons-material@^6.0.0
```
--------------------------------
### Run development server
Source: https://v6.mui.com/material-ui/migration/migrating-to-pigment-css
Command to start the development server after configuration.
```bash
npm run dev
```
--------------------------------
### Install Material UI with styled-components
Source: https://v6.mui.com/material-ui/getting-started/installation
Installs Material UI with the styled-components engine instead of the default Emotion.
```bash
npm install @mui/material @mui/styled-engine-sc styled-components
```
--------------------------------
### Wrap component with ThemeProvider
Source: https://v6.mui.com/material-ui/react-use-media-query
Example showing how to wrap a component with the ThemeProvider.
```jsx
```
--------------------------------
### Install Pigment CSS dependencies
Source: https://v6.mui.com/material-ui/migration/migrating-to-pigment-css
Install the required Material UI wrapper and Pigment CSS packages.
```bash
npm install @mui/material-pigment-css @pigment-css/react
```
--------------------------------
### Install Material UI Lab
Source: https://v6.mui.com/material-ui/about-the-lab
Command to install the lab package along with its required peer dependency, Material UI.
```bash
npm install @mui/lab@^6.0.0-beta @mui/material@^6.0.0
```
--------------------------------
### Install Material UI with npm
Source: https://v6.mui.com/material-ui/getting-started/installation
Installs the core Material UI package along with Emotion dependencies.
```bash
npm install @mui/material@^6.0.0 @emotion/react @emotion/styled
```
--------------------------------
### Render responsive components
Source: https://v6.mui.com/material-ui/customization/breakpoints
Example structure for components that respond to breakpoint-based styling.
```jsx
down(md): redup(md): blueup(lg): green
```
--------------------------------
### Basic Masonry Implementation
Source: https://v6.mui.com/material-ui/react-masonry
A simple example showing how to use the Masonry component with a fixed number of columns and spacing.
```jsx
{heights.map((height, index) => (
{index + 1}
))}
```
--------------------------------
### Install and Import Roboto Font
Source: https://v6.mui.com/material-ui/getting-started/installation
Installs the Roboto font via Fontsource and imports the necessary weights in the project entry point.
```bash
npm install @fontsource/roboto
```
```javascript
import '@fontsource/roboto/300.css';
import '@fontsource/roboto/400.css';
import '@fontsource/roboto/500.css';
import '@fontsource/roboto/700.css';
```
--------------------------------
### Install Dependencies for App Router
Source: https://v6.mui.com/material-ui/integrations/nextjs
Install the necessary Material UI and Emotion packages for Next.js App Router integration.
```bash
npm install @mui/material-nextjs @emotion/cache
```
--------------------------------
### Account Menu
Source: https://v6.mui.com/material-ui/react-menu
Example of integrating Menu with other components like Avatar.
```JSTS
import * as React from 'react';
import Box from '@mui/material/Box';
import Avatar from '@mui/material/Avatar';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip';
import PersonAdd from '@mui/icons-material/PersonAdd';
import Settings from '@mui/icons-material/Settings';
import Logout from '@mui/icons-material/Logout';
export default function AccountMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
ContactProfileM
);
}
```
--------------------------------
### Install Dependencies for Pages Router
Source: https://v6.mui.com/material-ui/integrations/nextjs
Install the necessary Material UI, Emotion, and Emotion server packages for Next.js Pages Router integration.
```bash
npm install @mui/material-nextjs @emotion/cache @emotion/server
```
--------------------------------
### Basic Stack Configuration
Source: https://v6.mui.com/material-ui/react-stack
Example of configuring a Stack component with direction, spacing, and alignment using the sx prop.
```jsx
```
--------------------------------
### Truncation Implementation Example
Source: https://v6.mui.com/material-ui/react-stack
A comparison of standard Stack layout versus one configured with min-width: 0 to support text truncation.
```jsx
W{message}W{message}
```
--------------------------------
### Theming with Generated Class Names
Source: https://v6.mui.com/material-ui/experimental-api/classname-generator
Example of using `[component]Classes` for theming, demonstrating how to reference generated class names like `outlinedInputClasses.notchedOutline`.
```javascript
+import { outlinedInputClasses } from '@mui/material/OutlinedInput';
const theme = createTheme({
components: {
MuiOutlinedInput: {
styleOverrides: {
root: {
- '& .MuiOutlinedInput-notchedOutline': {
+ [`& .${outlinedInputClasses.notchedOutline}`]: {
borderWidth: 1,
}
}
}
}
}
});
```
--------------------------------
### Install Vite Pigment CSS plugin
Source: https://v6.mui.com/material-ui/migration/migrating-to-pigment-css
Add the Pigment CSS plugin as a development dependency for Vite projects.
```bash
npm install --save-dev @pigment-css/vite-plugin
```
--------------------------------
### Custom Font Configuration
Source: https://v6.mui.com/material-ui/icons
Example of importing a custom font variant and configuring the Icon component to use it.
```javascript
import Icon from '@mui/material/Icon';
;
```
--------------------------------
### Basic Popper Implementation
Source: https://v6.mui.com/material-ui/react-popper
A simple example showing how to toggle a Popper component using an anchor element.
```jsx
The content of the Popper.
```
--------------------------------
### Install tss-react dependencies
Source: https://v6.mui.com/material-ui/migration/migrating-from-jss
Commands to add tss-react to your project using npm or yarn.
```bash
npm install tss-react
```
```bash
yarn add tss-react
```
--------------------------------
### Install Next.js Pigment CSS plugin
Source: https://v6.mui.com/material-ui/migration/migrating-to-pigment-css
Add the Pigment CSS plugin as a development dependency for Next.js projects.
```bash
npm install --save-dev @pigment-css/nextjs-plugin
```
--------------------------------
### theme.breakpoints.between(start, end)
Source: https://v6.mui.com/material-ui/customization/breakpoints
Generates a media query that matches screen widths between two specified breakpoints.
```APIDOC
## theme.breakpoints.between(start, end)
### Description
Returns a media query string that matches screen widths greater than the screen size given by the first argument (inclusive) and less than the screen size given by the second argument (exclusive).
### Arguments
- **start** (string | number) - Required - A breakpoint key or screen width in px.
- **end** (string | number) - Required - A breakpoint key or screen width in px.
### Returns
- **media query** (string) - A media query string.
```
--------------------------------
### Apply nonce to CSP header
Source: https://v6.mui.com/material-ui/guides/content-security-policy
Example of setting the CSP header with the generated nonce.
```javascript
header('Content-Security-Policy').set(
`default-src 'self'; style-src 'self' 'nonce-${nonce}';`,
);
```
--------------------------------
### Default Class Name Generation Example
Source: https://v6.mui.com/material-ui/experimental-api/classname-generator
Illustrates the default HTML output for a Button component, showing the generated class names.
```html
```
--------------------------------
### Customize component styles with classes
Source: https://v6.mui.com/material-ui/guides/api
Example of defining a style object with root and variant-specific classes for component customization.
```javascript
const styles = {
root: {
color: green[600],
'&$checked': {
color: green[500],
},
},
checked: {},
};
```
--------------------------------
### Generate MuiSwitch theme overrides
Source: https://v6.mui.com/material-ui/design-resources/material-ui-sync
Example of theme configuration generated by the Sync plugin to replicate an iOS-style Switch component.
```javascript
{
components: {
MuiSwitch: {
styleOverrides: {
root: {
'&.MuiSwitch-sizeMedium:has(.MuiSwitch-colorPrimary)': {
'&:has(.Mui-checked):not(:has(.Mui-disabled)):not(:has(.Mui-focusVisible))':
{
width: '40px',
height: '21px',
padding: '0',
'& .MuiSwitch-switchBase': {
transform: 'translateX(19px) translateY(2px)',
padding: '0',
'& .MuiSwitch-thumb': {
width: '17px',
height: '17px',
background: '#FAFAFA',
},
'& + .MuiSwitch-track': {
width: '38px',
height: '21px',
background: 'var(--mui-palette-success-light)',
opacity: '1',
},
},
},
},
},
},
},
},
}
```
--------------------------------
### Basic Button Component Usage
Source: https://v6.mui.com/material-ui/getting-started/learn
A minimal example demonstrating the implementation of a contained Button component within a React application.
```javascript
import * as React from 'react';
import Button from '@mui/material/Button';
export default function ButtonUsage() {
return ;
}
```
--------------------------------
### Fast track project creation
Source: https://v6.mui.com/material-ui/experimental-api/pigment-css
Use these commands to quickly scaffold a new Pigment CSS project.
```bash
curl https://codeload.github.com/mui/pigment-css/tar.gz/master | tar -xz --strip=2 pigment-css-master/examples/pigment-css-nextjs-ts
cd pigment-css-nextjs-ts
```
--------------------------------
### Example of an XSS vulnerability
Source: https://v6.mui.com/material-ui/guides/content-security-policy
An example of malicious script injection that a CSP header would block.
```html
```
--------------------------------
### Setup ClassNameGenerator
Source: https://v6.mui.com/material-ui/experimental-api/classname-generator
Basic setup for the ClassNameGenerator API. This file should be imported before any Material UI component imports.
```javascript
// create a new file called `MuiClassNameSetup.js` at the root or src folder.
import { unstable_ClassNameGenerator as ClassNameGenerator } from '@mui/material/className';
ClassNameGenerator.configure(
// Do something with the componentName
(componentName) => componentName,
);
```
--------------------------------
### Implement a basic media query with useMediaQuery
Source: https://v6.mui.com/material-ui/react-use-media-query
Demonstrates using the hook to detect if the viewport width is at least 600px.
```javascript
import * as React from 'react';
import useMediaQuery from '@mui/material/useMediaQuery';
export default function SimpleMediaQuery() {
const matches = useMediaQuery('(min-width:600px)');
return {`(min-width:600px) matches: ${matches}`};
}
```
--------------------------------
### Install Roboto font via npm
Source: https://v6.mui.com/material-ui/react-typography
Use this command to install the Roboto font package via npm.
```bash
npm install @fontsource/roboto
```
--------------------------------
### Basic Menu Implementation
Source: https://v6.mui.com/material-ui/react-menu
Demonstrates a standard menu that opens over an anchor element and closes upon selection.
```javascript
import * as React from 'react';
import Button from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
export default function BasicMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
);
}
```
```typescript
import * as React from 'react';
import Button from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
export default function BasicMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
);
}
```
--------------------------------
### theme.transitions.create(props, options)
Source: https://v6.mui.com/material-ui/customization/transitions
Creates a CSS transition string based on the provided properties and optional configuration for duration, easing, and delay.
```APIDOC
## theme.transitions.create(props, options)
### Description
Generates a CSS transition value that composes the specified CSS properties with defined duration, easing, and delay.
### Arguments
- **props** (string | string[]) - Required - A CSS property or list of properties to transition. Defaults to ['all'].
- **options** (object) - Optional - Configuration object.
- **options.duration** (string | number) - Optional - Duration of the transition. Defaults to theme.transitions.duration.standard.
- **options.easing** (string) - Optional - Easing function for the transition. Defaults to theme.transitions.easing.easeInOut.
- **options.delay** (string | number) - Optional - Delay for the transition. Defaults to 0.
### Returns
- **transition** (string) - A CSS transition value.
### Example
```javascript
theme.transitions.create(['background-color', 'transform']);
```
```
--------------------------------
### Basic Link Usage
Source: https://v6.mui.com/material-ui/react-link
Demonstrates standard link implementation and the use of color and variant props.
```jsx
Link
{'color="inherit"'}
{'variant="body2"'}
```
--------------------------------
### Initialize color scheme script
Source: https://v6.mui.com/material-ui/customization/css-theme-variables/configuration
Add InitColorSchemeScript to the root layout to ensure correct color scheme application.
```javascript
createTheme({
cssVariables: {
cssVarPrefix: 'any'
}
})
```
```javascript
import InitColorSchemeScript from '@mui/material/InitColorSchemeScript';
export default function RootLayout(props) {
return (
{/* must come before the element */}
{children}
);
}
```
--------------------------------
### Enable CSS theme variables
Source: https://v6.mui.com/material-ui/customization/css-theme-variables/usage
Initialize the theme with cssVariables set to true and wrap the application with ThemeProvider.
```jsx
import { ThemeProvider, createTheme } from '@mui/material/styles';
const theme = createTheme({ cssVariables: true });
function App() {
return {/* ...your app */};
}
```
--------------------------------
### Implement useRadioGroup example
Source: https://v6.mui.com/material-ui/react-radio-button
Demonstrates using the RadioGroup component with custom FormControlLabel components.
```jsx
} />
} />
```
--------------------------------
### Polyfill matchMedia for Testing
Source: https://v6.mui.com/material-ui/react-use-media-query
Use css-mediaquery to emulate matchMedia in environments like jsdom that do not support it natively.
```javascript
import mediaQuery from 'css-mediaquery';
function createMatchMedia(width) {
return (query) => ({
matches: mediaQuery.match(query, {
width,
}),
addEventListener: () => {},
removeEventListener: () => {},
});
}
describe('MyTests', () => {
beforeAll(() => {
window.matchMedia = createMatchMedia(window.innerWidth);
});
});
```
--------------------------------
### Accessibility configurations
Source: https://v6.mui.com/material-ui/react-divider
Examples for hiding the divider from screen readers or using it as a container for text.
```jsx
```
```jsx
Text element
```
--------------------------------
### Migrate Select classes
Source: https://v6.mui.com/material-ui/migration/migrating-from-deprecated-apis
Run this command to automatically migrate Select component classes.
```bash
npx @mui/codemod@latest deprecations/select-classes
```
--------------------------------
### Transform JSS to styled API
Source: https://v6.mui.com/material-ui/migration/migrating-from-jss
Example of refactoring a makeStyles component to use the styled API.
```javascript
import Typography from '@mui/material/Typography';
-import makeStyles from '@mui/styles/makeStyles';
+import { styled } from '@mui/material/styles';
-const useStyles = makeStyles((theme) => ({
- root: {
- display: 'flex',
- alignItems: 'center',
- backgroundColor: theme.palette.primary.main
- },
- cta: {
- borderRadius: theme.shape.radius
- },
- content: {
- color: theme.palette.common.white,
- fontSize: 16,
- lineHeight: 1.7
- },
-}))
+const PREFIX = 'MyCard';
+const classes = {
+ root: `${PREFIX}-root`,
+ cta: `${PREFIX}-cta`,
+ content: `${PREFIX}-content`,
+}
+const Root = styled('div')(({ theme }) => ({
+ [`&.${classes.root}`]: {
+ display: 'flex',
+ alignItems: 'center',
+ backgroundColor: theme.palette.primary.main
+ },
+ [`& .${classes.cta}`]: {
+ borderRadius: theme.shape.radius
+ },
+ [`& .${classes.content}`]: {
+ color: theme.palette.common.white,
+ fontSize: 16,
+ lineHeight: 1.7
+ },
+}))
export const MyCard = () => {
- const classes = useStyles();
return (
-
+
{/* The benefit of this approach is that the code inside Root stays the same. */}
...
-
+
)
}
```
--------------------------------
### Import Masonry component
Source: https://v6.mui.com/material-ui/api/masonry
Shows the available methods for importing the Masonry component from the @mui/lab package.
```javascript
import Masonry from '@mui/lab/Masonry';
// or
import { Masonry } from '@mui/lab';
```
--------------------------------
### Generated CSS theme variables
Source: https://v6.mui.com/material-ui/customization/theming
Example of the global stylesheet generated when CSS variables are enabled.
```css
:root {
--mui-palette-primary-main: #1976d2;
/* ...other variables */
}
```
--------------------------------
### Native HTML title attribute
Source: https://v6.mui.com/material-ui/react-tooltip
Example of using the native title attribute which acts as an accessible description.
```html
```
--------------------------------
### Implement Server-side Rendering Support
Source: https://v6.mui.com/material-ui/react-use-media-query
Provide a custom matchMedia implementation to useMediaQuery on the server to ensure hydration matches.
```javascript
import * as ReactDOMServer from 'react-dom/server';
import parser from 'ua-parser-js';
import mediaQuery from 'css-mediaquery';
import { createTheme, ThemeProvider } from '@mui/material/styles';
function handleRender(req, res) {
const deviceType = parser(req.headers['user-agent']).device.type || 'desktop';
const ssrMatchMedia = (query) => ({
matches: mediaQuery.match(query, {
// The estimated CSS width of the browser.
width: deviceType === 'mobile' ? '0px' : '1024px',
}),
});
const theme = createTheme({
components: {
// Change the default options of useMediaQuery
MuiUseMediaQuery: {
defaultProps: {
ssrMatchMedia,
},
},
},
});
const html = ReactDOMServer.renderToString(
,
);
// …
}
```
--------------------------------
### Implement responsive full-screen dialog
Source: https://v6.mui.com/material-ui/react-dialog
Uses useMediaQuery to toggle the fullScreen prop based on the theme's breakpoint.
```javascript
import useMediaQuery from '@mui/material/useMediaQuery';
function MyComponent() {
const theme = useTheme();
const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
return ;
}
```
--------------------------------
### Dynamic palette color override
Source: https://v6.mui.com/material-ui/migration/migrating-to-pigment-css
Example of a theme override using ownerState that requires migration to variants.
```javascript
const theme = createTheme({
components: {
MuiCard: {
styleOverrides: {
root: ({ theme, ownerState }) => ({
color: theme.palette[ownerState.palette]?.main,
}),
},
},
},
});
```
--------------------------------
### Grid Spacing Prop
Source: https://v6.mui.com/material-ui/react-grid
Example of applying the spacing prop to a grid container to manage gaps between items.
```JSX
```
--------------------------------
### Create a basic grid layout
Source: https://v6.mui.com/material-ui/react-grid2
Use the container prop to wrap grid items and define column widths using integer values from 1 to 12.
```jsx
size=8size=4size=4size=8
```
--------------------------------
### Custom Spacing Transformation
Source: https://v6.mui.com/material-ui/customization/spacing
Examples of overriding the default spacing behavior using different data types.
```javascript
const theme = createTheme({
spacing: 4,
});
theme.spacing(2); // `${4 * 2}px` = '8px'
```
```javascript
const theme = createTheme({
spacing: (factor) => `${0.25 * factor}rem`, // (Bootstrap strategy)
});
theme.spacing(2); // = 0.25 * 2rem = 0.5rem = 8px
```
```javascript
const theme = createTheme({
spacing: [0, 4, 8, 16, 32, 64],
});
theme.spacing(2); // = '8px'
```
--------------------------------
### Create a custom theme
Source: https://v6.mui.com/material-ui/customization/theming
Define custom palette colors by passing an options object to createTheme.
```javascript
import { createTheme } from '@mui/material/styles';
import { green, purple } from '@mui/material/colors';
const theme = createTheme({
palette: {
primary: {
main: purple[500],
},
secondary: {
main: green[500],
},
},
});
```
--------------------------------
### Basic Grid Layout
Source: https://v6.mui.com/material-ui/react-grid
Demonstrates a simple grid container with items using fixed column widths across breakpoints.
```JSX
xs=8xs=4xs=4xs=8
```
--------------------------------
### Run ListItemButton Codemod
Source: https://v6.mui.com/material-ui/migration/upgrade-to-v6
Automate the migration of ListItem components to ListItemButton.
```bash
npx @mui/codemod@latest v6.0.0/list-item-button-prop
```
--------------------------------
### Transform basic JSS makeStyles to tss-react
Source: https://v6.mui.com/material-ui/migration/migrating-from-jss
Example showing the conversion of a standard makeStyles implementation to the tss-react pattern.
```typescript
import * as React from 'react';
-import makeStyles from '@material-ui/styles/makeStyles';
+import { makeStyles } from 'tss-react/mui';
import Button from '@mui/material/Button';
import Link from '@mui/material/Link';
-const useStyles = makeStyles((theme) => {
+const useStyles = makeStyles()((theme) => {
return {
root: {
color: theme.palette.primary.main,
},
apply: {
marginRight: theme.spacing(2),
},
};
});
function Apply() {
- const classes = useStyles();
+ const { classes } = useStyles();
return (
);
}
export default Apply;
```
--------------------------------
### Boolean Prop Type Definition
Source: https://v6.mui.com/material-ui/guides/api
Example of using boolean props for component variations, enabling shorthand notation.
```typescript
type Props = {
contained: boolean;
fab: boolean;
};
```
--------------------------------
### Run Backdrop Codemod
Source: https://v6.mui.com/material-ui/migration/migrating-from-deprecated-apis
Execute the codemod to automatically migrate Backdrop props.
```bash
npx @mui/codemod@latest deprecations/backdrop-props
```
--------------------------------
### Naive Portal Implementation
Source: https://v6.mui.com/material-ui/getting-started/faq
A basic implementation of a Portal component that uses a ref to determine when to mount its children. This version has limitations in handling ref availability and DOM node changes.
```jsx
function Portal({ children, container }) {
const [node, setNode] = React.useState(null);
React.useEffect(() => {
setNode(container.current);
}, [container]);
if (node === null) {
return null;
}
return ReactDOM.createPortal(children, node);
}
```
--------------------------------
### Compose theme options
Source: https://v6.mui.com/material-ui/customization/theming
Create a theme in multiple steps when subsequent options depend on values defined in previous steps.
```javascript
import { createTheme } from '@mui/material/styles';
let theme = createTheme({
palette: {
primary: {
main: '#0052cc',
},
secondary: {
main: '#edf2ff',
},
},
});
theme = createTheme(theme, {
palette: {
info: {
main: theme.palette.secondary.main,
},
},
});
```
--------------------------------
### Usage of custom variants in JSX
Source: https://v6.mui.com/material-ui/customization/theme-components
Example of applying the custom 'dashed' variant to Button components within a ThemeProvider.
```jsx
```
--------------------------------
### Run codemods for migration
Source: https://v6.mui.com/material-ui/customization/dark-mode
Use the provided codemods to automatically migrate from theme.palette.mode to theme.applyStyles().
```bash
npx @mui/codemod@latest v6.0.0/styled
npx @mui/codemod@latest v6.0.0/sx-prop
npx @mui/codemod@latest v6.0.0/theme-v6
```
--------------------------------
### Implement a range slider
Source: https://v6.mui.com/material-ui/react-slider
Use an array of values for the value prop to define the start and end points of a range.
```JSX
'Temperature range'}
value={value}
onChange={handleChange}
valueLabelDisplay="auto"
getAriaValueText={valuetext}
/>
```
--------------------------------
### Define primary color tokens
Source: https://v6.mui.com/material-ui/customization/palette
Example structure of the default primary color object used in Material UI themes.
```javascript
const primary = {
main: '#1976d2',
light: '#42a5f5',
dark: '#1565c0',
contrastText: '#fff',
};
```
--------------------------------
### Apply a custom theme with ThemeProvider
Source: https://v6.mui.com/material-ui/customization/theming
Use this to wrap your application root with a custom theme object. The theme is created using createTheme and merged with the default theme.
```javascript
import * as React from 'react';
import { red } from '@mui/material/colors';
import { ThemeProvider, createTheme } from '@mui/material/styles';
const theme = createTheme({
palette: {
primary: {
main: red[500],
},
},
});
function App() {
return ...;
}
```
--------------------------------
### Configure Custom Filter Options
Source: https://v6.mui.com/material-ui/react-autocomplete
Use createFilterOptions to restrict matching to the start of the string and define a custom stringify function.
```javascript
const filterOptions = createFilterOptions({
matchFrom: 'start',
stringify: (option) => option.title,
});
;
```
--------------------------------
### Listen for leading events
Source: https://v6.mui.com/material-ui/react-click-away-listener
Configures the listener to respond to the start of a click or touch event instead of the default trailing event.
```jsx
{open ? (
Click me, I will stay visible until you click outside.
) : null}
```
--------------------------------
### Implement theme.applyStyles utility
Source: https://v6.mui.com/material-ui/migration/upgrade-to-v6
Use theme.applyStyles to manage color mode styles, replacing manual checks against theme.palette.mode.
```javascript
const MyComponent = styled('button')(({ theme }) => ({
padding: '0.5rem 1rem',
border: '1px solid,
- borderColor: theme.palette.mode === 'dark' ? '#fff' : '#000',
+ borderColor: '#000',
+ ...theme.applyStyles('dark', {
+ borderColor: '#fff',
+ })
}))
```
--------------------------------
### Implement Custom Input Component
Source: https://v6.mui.com/material-ui/react-text-field
Example of creating a custom input component using React.forwardRef and useImperativeHandle to integrate with third-party libraries.
```javascript
const MyInputComponent = React.forwardRef((props, ref) => {
const { component: Component, ...other } = props;
// implement `InputElement` interface
React.useImperativeHandle(ref, () => ({
focus: () => {
// logic to focus the rendered component from 3rd party belongs here
},
// hiding the value e.g. react-stripe-elements
}));
// `Component` will be your `SomeThirdPartyComponent` from below
return ;
});
// usage
;
```
--------------------------------
### Basic Backdrop Implementation
Source: https://v6.mui.com/material-ui/react-backdrop
Displays a Backdrop with a CircularProgress indicator. Requires state management for the open/close functionality.
```JSX
({ color: '#fff', zIndex: theme.zIndex.drawer + 1 })}
open={open}
onClick={handleClose}
>
```
--------------------------------
### Enum Prop Type Definition
Source: https://v6.mui.com/material-ui/guides/api
Example of using an enum for component variations to prevent invalid combinations and support future extensibility.
```typescript
type Props = {
variant: 'text' | 'contained' | 'fab';
};
```
--------------------------------
### Grid with Multiple Breakpoints
Source: https://v6.mui.com/material-ui/react-grid
Shows how to define different column widths for various screen sizes using breakpoint props.
```JSX
xs=6 md=8xs=6 md=4xs=6 md=4xs=6 md=8
```
--------------------------------
### Implement basic Input components
Source: https://v6.mui.com/material-ui/react-text-field
Demonstrates standard Input usage with default values, placeholders, disabled states, and error states.
```JSTS
```
--------------------------------
### Check for legacy Material UI v4 dependencies
Source: https://v6.mui.com/material-ui/migration/troubleshooting
Use these commands to identify if any installed packages still rely on the legacy @material-ui/core package.
```bash
$ npm ls @material-ui/core
project@0.1.0 /path/to/project
└─┬ @mui/x-data-grid@4.0.0
└── @material-ui/core@4.12.3
```
--------------------------------
### Run InputBase Codemods
Source: https://v6.mui.com/material-ui/migration/migrating-from-deprecated-apis
Use these commands to automatically migrate InputBase props and classes in your project.
```bash
npx @mui/codemod@latest deprecations/input-base-props
npx @mui/codemod@latest deprecations/input-base-classes
```
--------------------------------
### Tooltip labeling and description
Source: https://v6.mui.com/material-ui/react-tooltip
Demonstrates standard Tooltip usage and the describeChild prop for accessible descriptions.
```jsx
```
```jsx
```