Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Practice Exercises and Cheat Sheet

Test your Material UI skills with ten theming, navigation, performance and Next.js exercises, then keep a compact cheat sheet of sx shortcuts, theme keys and patterns.

You now know how to theme Material UI, build navigation and data display, keep a bundle small, set up Next.js and test components. Knowledge sticks when you use it, so this lesson gives you ten exercises with hints and short solutions, a runnable sx shortcut explorer and a cheat sheet that you can come back to.

Material UI cannot run in the live editors on this site, so the solutions are real MUI code shown read-only. To run them, create a project (for example with Vite, see Tooling: TypeScript, Testing and Migration) and paste them in. The preview below is a stand-in that you can run here.

Exercises

Try each one before you read the hint. Do them in a real project if you can.

1. A brand theme

Create a theme with a green primary, a pink secondary, 12px rounded corners, no uppercase buttons, and a Button that has disableElevation by default. Show a contained button and a text field.

Hint: palette, shape.borderRadius, and components.MuiButton with defaultProps and styleOverrides.

TSX
// Real Material UI, read-only
const theme = createTheme({
  palette: { primary: { main: '#0b6e4f' }, secondary: { main: '#d1495b' } },
  shape: { borderRadius: 12 },
  components: {
    MuiButton: {
      defaultProps: { disableElevation: true },
      styleOverrides: { root: { textTransform: 'none' } },
    },
  },
});

2. Dark mode with a persistent choice

Add a toggle button that switches between light, dark and system, without any flash on reload.

Hint: cssVariables, colorSchemes, useColorScheme, InitColorSchemeScript. See Dark Mode and Color Schemes.

3. A custom variant

Add variant="dashed" to Button (a dashed outline). Make TypeScript accept it.

Hint: the variants array in the theme and ButtonPropsVariantOverrides augmentation. See Component Overrides and Variants.

4. A reusable styled component

Write a Pill using styled('span') that takes a tone prop (info, success, danger) and does not leak tone to the DOM.

TSX
// Real Material UI, read-only
const Pill = styled('span', { shouldForwardProp: (p) => p !== 'tone' })<{ tone: 'info' | 'success' | 'danger' }>(
  ({ theme, tone }) => ({
    padding: theme.spacing(0.25, 1.5),
    borderRadius: 999,
    backgroundColor: theme.palette[tone].light,
    color: theme.palette[tone].contrastText,
  }),
);

5. Responsive navigation

Build a shell with an AppBar, a permanent Drawer from md up and a temporary one below. Highlight the current page and make it keyboard accessible.

Hint: two drawers with display: { xs: 'none', md: 'block' }; ListItemButton selected. See App Bar and Drawer Navigation.

6. Breadcrumbs from a route

Given the path /catalog/shoes/trail-runner, render breadcrumbs where every segment is a link except the last, which is the current page.

Hint: split the path, accumulate the URL, and map to Link; the last item is a Typography with aria-current="page".

7. A table that does not lag

Render 20,000 rows. First with a plain Table and measure; then fix it with pagination, then with virtualization.

Hint: the Profiler, Rendering Performance and sx Cost, and the Data Grid.

8. Cut the bundle

Take a project that imports { Button, TextField } from '@mui/material' and { Menu } from '@mui/icons-material'. Change the imports to path imports, add a lint rule that enforces it, and lazy-load a heavy route.

Hint: Bundle Size and Imports.

9. Next.js setup

Create a Next.js App Router project with MUI: cache provider, theme in a client component, next/font, color scheme script and one server page that renders a client Button.

Hint: Next.js App Router Setup.

10. Test it

Write Testing Library tests for a login form: an error shows after blur on an invalid email, the Submit button is disabled while sending, and a success message appears.

Hint: screen.getByRole('button', { name: /sign in/i }), userEvent, findByRole('alert').

Try it: an sx shortcut explorer

When you are unsure what a shortcut produces, test it. This stand-in explains the common sx keys: pick one, enter a value and see the CSS and the explanation.

What does this sx shortcut produce?

Try it: build a pricing card

A final exercise you can run here: complete the pricing card stand-in. It has a plan toggle (monthly or yearly) that changes the price. Task: make the "Popular" plan stand out with a border in the primary color and a small Chip, and make the three cards stack on narrow screens. The starter works; change the CSS and JSX, and use what you learned about sx (here as inline style) and theme values (here as variables).

Starter: pricing cards with a billing toggle

Cheat sheet

Setup

Task Code
Install npm i @mui/material @emotion/react @emotion/styled
Icons npm i @mui/icons-material and import MenuIcon from '@mui/icons-material/Menu'
Font @fontsource/roboto weights 300, 400, 500, 700
Providers ThemeProvider theme={theme} then CssBaseline
Next.js @mui/material-nextjs with AppRouterCacheProvider; theme in a 'use client' file

Theme

Need Where
Colors palette.primary.main, secondary, error, warning, info, success, text, background
Fonts typography.fontFamily, typography.h1...h6, body1, button
Spacing unit spacing: 8 and theme.spacing(n)
Corners shape.borderRadius
Breakpoints xs 0, sm 600, md 900, lg 1200, xl 1536
Dark mode cssVariables: true, colorSchemes: { dark: true }, useColorScheme(), InitColorSchemeScript
Defaults for a component components.MuiXxx.defaultProps
CSS for a component components.MuiXxx.styleOverrides
New variant components.MuiXxx.variants plus TypeScript augmentation

sx shortcuts

Key Meaning
p, px, py, pt, pr, pb, pl padding, multiples of the spacing unit
m, mx, my, mt, mr, mb, ml margin
gap, rowGap, columnGap gaps
bgcolor, color, borderColor palette paths such as 'primary.main'
borderRadius multiplies shape.borderRadius
boxShadow index into theme.shadows
typography spreads a typography variant, such as 'body2'
display, flexDirection, alignItems, justifyContent normal CSS, accept responsive objects
{ xs: .., md: .. } or [a, b, c] responsive values (mobile first)
'&:hover', '& .child', '&.Mui-selected' nested selectors
theme.applyStyles('dark', {...}) styles for one color scheme

Layout

Component Use
Container maxWidth="lg" centered page width
Stack spacing={2} direction="row" one-dimensional layouts
Grid container spacing={2} with Grid size={{ xs: 12, md: 6 }} 12-column responsive grid
Box component="section" a styled wrapper with the right element
Need Component
Header AppBar + Toolbar (spacer <Toolbar /> when fixed)
Side menu Drawer (temporary, persistent, permanent) with List and ListItemButton
Sections of a page Tabs + Tab (controlled value)
Actions list Menu with anchorEl state and MenuItem
Path Breadcrumbs (last item aria-current="page")
Data Table family, TableSortLabel, TablePagination, or the MUI X DataGrid
Decision Dialog
Message Snackbar with Alert (inline: Alert)
Waiting Skeleton, CircularProgress, LinearProgress, Backdrop

Performance

  • Path imports; icons from their own files.
  • lazy plus Suspense for routes and heavy components.
  • Create the theme once at module scope; use CSS variable color schemes.
  • Stable sx objects on repeated elements or use styled.
  • Push state down; memoize expensive children; virtualize long lists.
  • Profile in production mode.

Accessibility reminders

  • Icon-only buttons need aria-label.
  • Use component to keep correct elements and heading order.
  • Mark the current page with aria-current, label landmarks with aria-label.
  • Do not rely on color alone; keep focus visible.
  • Test by role and label with Testing Library.

What to learn next

  • Layout and forms in depth: review the earlier chapters of this track for Grid, Stack, TextField, Select and Autocomplete.
  • React itself: hooks, context and patterns in the React tutorial.
  • Routing: React Router for navigation that works with ListItemButton and Tabs.
  • MUI X: Data Grid, Date Pickers and Charts for advanced data screens.
  • A design system: create your own src/ui layer and publish it for your team.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is the best narrow tool to style a single element once?

    sx is meant for one-off styles. Use styled for reuse and the theme for app-wide changes.
  2. 2. A page has 20,000 rows. Which approach scales?

    Rendering all rows creates tens of thousands of DOM nodes. Pagination or virtualization limits the work.
  3. 3. Where should the ThemeProvider live in a Next.js App Router app?

    Context providers need client rendering, so the provider sits in a client component used by the layout.
  4. 4. What is the first step in performance work?

    Measure first, so you fix what really is slow or large.

Summary

  • The exercises cover theming, dark mode, variants, styled components, navigation, tables, bundle size, Next.js and tests.
  • The sx explorer and pricing card stand-ins give you something to run and modify here.
  • The cheat sheet lists setup, theme keys, sx shortcuts, layout, navigation and data components, performance habits and accessibility reminders.
  • Keep building: each project in this chapter is a pattern you will reuse.

Next: Material UI tutorial overview