Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Performance and Patterns

Composition and Custom Components

Build your own components on Material UI: the component prop, wrapping with ref and sx forwarding, router links, polymorphic components and design-system patterns.

Using Material UI well is mostly about composition: building your own small components out of MUI parts, so the rest of the app talks to a vocabulary that fits your product (PrimaryButton, FormField, PageHeader) and not to forty props of a library. Done well, this keeps design decisions in one place and makes a future library upgrade a small change. Done carelessly, it hides props, breaks refs and loses accessibility.

This lesson covers the patterns that work: the component prop, wrapping and forwarding props, passing refs, router integration, and a design-system layer.

MUI is not available in the live editors here. The real MUI code is read-only; the runnable examples are stand-ins that show the same React patterns.

The component prop

Almost every MUI component takes a component prop that changes the element it renders. This is how you keep MUI's styling while choosing correct HTML:

JSX
// Real Material UI, read-only
<Typography variant="h4" component="h2">Section title</Typography>
<Button component="a" href="/pricing">Pricing</Button>
<ListItemButton component={RouterLink} to="/reports">Reports</ListItemButton>
<Paper component="article" elevation={0}>...</Paper>
<Box component="form" onSubmit={handleSubmit} noValidate>...</Box>

Typography's variant controls how the text looks, and component controls the element (and therefore the document outline). Do not use variant="h1" just for size on a <span>, and do not skip heading levels. Use Box component="nav", "section", "ul" and friends for landmarks and lists.

MUI's Link and Button render <a> when you give them href, which causes a full page load in a single-page app. To use the router, pass its link component:

JSX
// Real Material UI + React Router, read-only
import { Link as RouterLink } from 'react-router';
import Link from '@mui/material/Link';
import Button from '@mui/material/Button';

<Link component={RouterLink} to="/settings" underline="hover">Settings</Link>
<Button component={RouterLink} to="/new" variant="contained">New project</Button>

To make every MUI link use the router by default, set it once in the theme:

JSX
// Real Material UI + React Router, read-only
const LinkBehavior = forwardRef(function LinkBehavior({ href, ...other }, ref) {
  return <RouterLink ref={ref} to={href} {...other} />;
});

const theme = createTheme({
  components: {
    MuiLink: { defaultProps: { component: LinkBehavior } },
    MuiButtonBase: { defaultProps: { LinkComponent: LinkBehavior } },
  },
});

With that, <Button href="/new"> renders a router link. The same idea works for Next.js (next/link).

When you pass a custom component, it must forward the ref and spread the rest of its props onto the DOM element. Otherwise ripples, tooltips and focus management cannot attach to it. In React 19, ref is an ordinary prop for function components; in older React versions you need forwardRef.

Wrapping a component

A wrapper should accept all the props of the thing it wraps, add your defaults, and merge sx properly:

JSX
// Real Material UI, read-only
import Button from '@mui/material/Button';

export function PrimaryButton({ sx, ...props }) {
  return (
    <Button
      variant="contained"
      color="primary"
      {...props}
      sx={[
        { textTransform: 'none', borderRadius: 999 },
        ...(Array.isArray(sx) ? sx : [sx]),
      ]}
    />
  );
}

Points that make a wrapper good:

  • Spread the rest ({...props}) so every prop of the original (onClick, disabled, aria-*, href) keeps working.
  • Put your defaults before the spread so callers can override them, and put things you do not want overridden after it.
  • Merge sx as an array so a caller's style does not erase yours (and callbacks keep working).
  • Type it with the wrapped component's props: ButtonProps from @mui/material/Button.
  • Prefer theme defaultProps/variants over a wrapper if all you do is set defaults; use a wrapper when you add behavior or structure.
TSX
// Real Material UI + TypeScript, read-only
import Button, { ButtonProps } from '@mui/material/Button';

type PrimaryButtonProps = Omit<ButtonProps, 'variant' | 'color'> & { loading?: boolean };

Try it: a wrapper that merges and forwards

This stand-in has a Button that accepts sx as an object, a function or an array, like MUI. PrimaryButton wraps it with defaults and merges the caller's style. Click the buttons and read what each receives.

A wrapper that spreads props and merges sx

Polymorphic components

A polymorphic component renders different elements (as or component) and types its props accordingly. You rarely need to write your own; MUI's OverridableComponent types do it. With plain JavaScript the pattern is a few lines, and the stand-in below shows it with the right ref and prop forwarding.

A polymorphic Text component

A design-system layer

Teams often keep a folder (for example src/ui/) that re-exports MUI with project decisions applied:

TEXT
src/ui/
  index.js           re-exports everything the app may use
  theme.js           createTheme with tokens and component overrides
  PrimaryButton.jsx
  FormField.jsx      TextField with consistent label, helper and error wiring
  PageHeader.jsx     title, breadcrumbs, actions
  DataTable.jsx      Table with sorting, paging and empty state

Benefits: the app imports from one place (import { FormField } from '@/ui'), design changes happen in one file, and it is easy to replace a MUI component with another implementation. Costs: wrappers need maintenance, and thin wrappers that only rename props add little. Wrap when you add something: a consistent error display, loading state, analytics, permissions or accessible defaults.

A FormField example

JSX
// Real Material UI, read-only
import TextField from '@mui/material/TextField';
import { useId } from 'react';

export function FormField({ label, error, helperText, ...props }) {
  const id = useId();
  return (
    <TextField
      id={id}
      label={label}
      error={Boolean(error)}
      helperText={error ?? helperText}
      fullWidth
      margin="normal"
      {...props}
    />
  );
}

MUI's TextField already links the label, input and helper text with the right ids if you pass an id. Wrapping it once makes sure you never forget.

Compound and slot patterns

For flexible components, expose slots the way MUI does: slots and slotProps let callers replace or configure inner parts without a long list of special props. Another option is composition by children (<Card><Card.Header/>...). Choose slots when a component has several optional inner parts (an Alert with icon and action). Choose plain children when the structure is yours to define. The component design lessons in the React tutorial cover the compound pattern in depth.

Accessibility is part of the wrapper

When you wrap, you own accessibility:

  • Do not swallow aria-* props; spread them.
  • Keep visible labels. An icon-only wrapper needs a required aria-label prop (make it required in TypeScript).
  • Keep native elements: a Button with component="div" loses keyboard support and role. Prefer the default <button>, or <a> with href.
  • Do not trap focus or reorder tab order unless you are building a widget that needs it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the component prop on Typography control?

    variant picks the style from the theme; component picks the element, such as h2 or p, which affects semantics.
  2. 2. How should a wrapper merge a caller's sx with its own defaults?

    The array form combines objects, functions and arrays safely, so the caller can still customize.
  3. 3. Why must a custom component passed as component or LinkComponent forward its ref?

    MUI needs access to the DOM element. In React 19 ref is a normal prop; older versions need forwardRef.
  4. 4. When is a wrapper component better than theme defaultProps?

    Theme defaults are enough for simple presets. Wrappers pay off when they add something.

Summary

  • component changes the rendered element; variant changes the look. Use semantic elements.
  • Pass the router's link component through component, or set it once in the theme with LinkBehavior.
  • Good wrappers spread props, put defaults before the spread, merge sx as an array and forward refs.
  • A src/ui layer centralizes decisions; wrap only when you add value.
  • Wrappers inherit responsibility for accessibility.

Next: Next.js App Router Setup