Material-UI is a very popular React UI framework based on Google’s Material Design language. It provides rich components and tools to help developers quickly build beautiful, responsive user interfaces. Below is a detailed explanation of Material-UI’s core knowledge points, covering its basic concepts, usage methods, main features, and some practical tips.
1. What is Material-UI?
Material-UI (now renamed to MUI) is a React component library aimed at implementing Material Design specifications. It provides pre-built components (such as buttons, input fields, cards, etc.) that are both beautiful and powerful, while supporting high customization. MUI’s goal is to let developers focus on business logic rather than designing UI from scratch.
- Current Version: As of April 2025, the latest stable version of MUI is v5.x (there may be updates, please check the official website).
- Core Libraries:
@mui/material(main component library),@mui/system(styling tools),@mui/icons-material(icon library).
2. Installation and Basic Usage
To start using Material-UI, you first need to install it in your React project.
Installation
npm install @mui/material @emotion/react @emotion/styled
@emotion/reactand@emotion/styledare the default styling engines for MUI v5.- If you need the icon library:
npm install @mui/icons-material
Basic Configuration
Import ThemeProvider and CSS baseline in your project’s root component:
import * as React from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
const theme = createTheme();
function App() {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<div>
<h1>Hello, Material-UI!</h1>
</div>
</ThemeProvider>
);
}
export default App;
ThemeProvider: Used to apply a global theme.CssBaseline: Normalizes browser default styles to ensure consistency.
3. Core Components
Material-UI provides many ready-to-use components. Here are some commonly used ones:
(1) Button
import Button from '@mui/material/Button';
function MyComponent() {
return (
<Button variant="contained" color="primary">
Click Me
</Button>
);
}
variant: Button style (contained,outlined,text).color: Color (primary,secondary, etc.).
(2) Text Input (TextField)
import TextField from '@mui/material/TextField';
function MyComponent() {
return <TextField label="Enter content" variant="outlined" />;
}
variant: Input field style (outlined,filled,standard).
(3) Grid Layout
import Grid from '@mui/material/Grid';
function MyComponent() {
return (
<Grid container spacing={2}>
<Grid item xs={6}>
<div>Left Half</div>
</Grid>
<Grid item xs={6}>
<div>Right Half</div>
</Grid>
</Grid>
);
}
container: Defines a grid container.item: Defines a grid item.xs: Responsive breakpoint (12-column layout,xs=6means half width).
(4) Card
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
function MyComponent() {
return (
<Card>
<CardContent>
<h2>Card Title</h2>
<p>Card Content</p>
</CardContent>
</Card>
);
}
4. Theming and Customization
Material-UI’s theming system is very powerful, allowing developers to customize colors, typography, spacing, and more.
Creating a Custom Theme
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
palette: {
primary: {
main: '#1976d2', // Custom primary color
},
secondary: {
main: '#dc004e',
},
},
typography: {
fontFamily: 'Roboto, Arial, sans-serif',
h1: {
fontSize: '2.5rem',
},
},
});
function App() {
return (
<ThemeProvider theme={theme}>
<Button variant="contained" color="primary">
Custom Button
</Button>
</ThemeProvider>
);
}
Dynamic Theming
You can switch themes through state, for example, to implement dark mode:
const lightTheme = createTheme({ palette: { mode: 'light' } });
const darkTheme = createTheme({ palette: { mode: 'dark' } });
function App() {
const [darkMode, setDarkMode] = React.useState(false);
return (
<ThemeProvider theme={darkMode ? darkTheme : lightTheme}>
<CssBaseline />
<Button onClick={() => setDarkMode(!darkMode)}>
Toggle Theme
</Button>
</ThemeProvider>
);
}
5. Styling System
MUI provides multiple ways to add styles to components.
(1) sx Prop
sx is a core feature of MUI, allowing you to write styles directly on components:
<Button sx={{ bgcolor: 'red', color: 'white', '&:hover': { bgcolor: 'darkred' } }}>
Red Button
</Button>
- Supports theme values:
sx={{ mt: 2 }}(using the theme’s spacing unit). - Supports pseudo-classes:
&:hover.
(2) styled API
Use @mui/system to create custom styled components:
import { styled } from '@mui/material/styles';
const CustomDiv = styled('div')(({ theme }) => ({
backgroundColor: theme.palette.primary.main,
padding: theme.spacing(2),
}));
function MyComponent() {
return <CustomDiv>Custom Div</CustomDiv>;
}
(3) CSS Modules or Emotion
You can also combine traditional CSS files or the Emotion library for style management.
6. Responsive Design
Material-UI has built-in support for responsive design, mainly through Grid and useMediaQuery.
Using Grid for Responsive Layout
<Grid container spacing={2}>
<Grid item xs={12} sm={6} md={4}>
<div>Full width on small screens, half on medium screens, one-third on large screens</div>
</Grid>
</Grid>
useMediaQuery Hook
Detect screen size and adjust dynamically:
import { useMediaQuery } from '@mui/material';
function MyComponent() {
const isSmallScreen = useMediaQuery('(max-width:600px)');
return <div>{isSmallScreen ? 'Small Screen' : 'Large Screen'}</div>;
}
7. Utility Tools and Extensions
- Icons: Use Material Icons through
@mui/icons-material:import DeleteIcon from '@mui/icons-material/Delete'; <Button startIcon={<DeleteIcon />}>Delete</Button> - Date Picker: Requires additional installation of
@mui/x-date-pickers:npm install @mui/x-date-pickers @date-io/date-fnsimport { DatePicker } from '@mui/x-date-pickers/DatePicker'; <DatePicker label="Select Date" />
8. Performance Optimization
- Lazy Loading: Avoid importing the entire
@mui/material, only import the components you need. - Virtualization: For long lists, use virtualized versions of
@mui/material/List(such as@mui/x-data-grid). - Avoid Repeated Rendering: Use
React.memooruseMemoto optimize components.
9. Common Issues and Tips
- Migration from v4 to v5: v5 uses Emotion instead of JSS, pay attention to updating style syntax.
- Debugging Styles: Use browser developer tools to inspect class names generated by
sx. - Chinese Support: Ensure fonts support Chinese, for example by setting
fontFamily: 'Noto Sans SC'.
Summary
Material-UI (MUI) is a powerful and flexible React UI framework suitable for rapid development of high-quality interfaces. By mastering its components, theming system, and styling tools, you can easily build modern web applications. If you have specific questions or need code examples, feel free to ask further!
Comments