Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] Add overriding-component-structure doc to Material UI #45186

Merged
merged 16 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as React from 'react';
import PropTypes from 'prop-types';
import Box from '@mui/material/Box';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';

function PopperComponent(props) {
const { disablePortal, anchorEl, open, ...other } = props;
return <div {...other} />;
}

PopperComponent.propTypes = {
anchorEl: PropTypes.any,
disablePortal: PropTypes.bool,
open: PropTypes.bool.isRequired,
};

export default function OverridingInternalSlot() {
return (
<Box
sx={{ display: 'flex', flexDirection: 'column', width: 320, minHeight: 220 }}
>
<Autocomplete
open
options={['🆘 Need help', '✨ Improvement', '🚀 New feature', '🐛 Bug fix']}
renderInput={(params) => <TextField {...params} />}
slots={{
popper: PopperComponent,
}}
/>
</Box>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import * as React from 'react';
import Box from '@mui/material/Box';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';

interface PopperComponentProps {
anchorEl?: any;
disablePortal?: boolean;
open: boolean;
}

function PopperComponent(props: PopperComponentProps) {
const { disablePortal, anchorEl, open, ...other } = props;
return <div {...other} />;
}

export default function OverridingInternalSlot() {
return (
<Box
sx={{ display: 'flex', flexDirection: 'column', width: 320, minHeight: 220 }}
>
<Autocomplete
open
options={['🆘 Need help', '✨ Improvement', '🚀 New feature', '🐛 Bug fix']}
renderInput={(params) => <TextField {...params} />}
slots={{
popper: PopperComponent,
}}
/>
</Box>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Autocomplete
open
options={['🆘 Need help', '✨ Improvement', '🚀 New feature', '🐛 Bug fix']}
renderInput={(params) => <TextField {...params} />}
slots={{
popper: PopperComponent,
}}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as React from 'react';
import Button from '@mui/material/Button';

export default function OverridingRootSlot() {
return (
<Button
component="a"
href="https://mui.com/about/"
target="_blank"
rel="noopener"
>
About us
</Button>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as React from 'react';
import Button from '@mui/material/Button';

export default function OverridingRootSlot() {
return (
<Button
component="a"
href="https://mui.com/about/"
target="_blank"
rel="noopener"
>
About us
</Button>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Button
component="a"
href="https://mui.com/about/"
target="_blank"
rel="noopener"
>
About us
</Button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Overriding component structure

<p class="description">Learn how to override the default DOM structure of Material UI components.</p>

Material UI components are designed to suit the widest possible range of use cases, but you may occasionally need to change how a component's structure is rendered in the DOM.

To understand how to do this, it helps to know a bit about how the API design has evolved over time, and to have an accurate mental model of the components themselves.

## Context

Prior to Material UI v6, it was not possible to override the structure of most components in the library.
Some components had `*Props` props that allowed you to pass props to a specific slot, but this pattern was not applied consistently.

In v6, those props were deprecated in favor of the `slots` and `slotProps` props, which allow for more granular control over the structure of a component and make the API more consistent across the library.

To see the available slots for a component, refer to the slots sections of the respective component API documentation.

## The mental model

A component's structure is determined by the elements that fill that component's **slots**.
Slots are most commonly filled by HTML tags, but may also be filled by React components.

All components contain a root slot that defines their primary node in the DOM tree; more complex components also contain additional interior slots named after the elements they represent.

All _non-utility_ Material UI components accept two props for overriding their rendered HTML structure:

- `component`—to override the root slot
- `slots`—to replace any interior slots (when present) as well as the root

Additionally, you can pass custom props to interior slots using `slotProps`.

## The root slot

The root slot represents the component's outermost element. It is filled by a styled component with an appropriate HTML element.

For example, the [Button's](/material-ui/react-button/) root slot is a `<button>` element.
This component _only_ has a root slot; more complex components may have additional [interior slots](#interior-slots).

### The component prop

Use the `component` prop to override a component's root slot.
The demo below shows how to replace the Button's `<button>` tag with a `<a>` to create a link button:

{{"demo": "OverridingRootSlot.js"}}

:::info
The `href`, `target`, and `rel` props are specific to `<a>` tags.
When using the `component` prop, be sure to add the appropriate attributes that correspond to the element you're inserting.
:::

## Interior slots

Complex components are composed of one or more interior slots in addition to the root.
These slots are often (but not necessarily) nested within the root.

For example, the [Autocomplete](/material-ui/react-autocomplete/) is composed of a root `<div>` that houses several interior slots named for the elements they represent: input, startDecorator, endDecorator, clearIndicator, popupIndicator, and more.

### The slots prop

Use the `slots` prop to replace a component's interior slots.
The example below shows how to replace the popper slot in the [Autocomplete](/material-ui/react-autocomplete/) component to remove the popup functionality:

{{"demo": "OverridingInternalSlot.js"}}

### The slotProps prop

The `slotProps` prop is an object that contains the props for all slots within a component.
You can use it to define additional custom props to pass to a component's interior slots.

For example, the code snippet below shows how to add a custom `data-testid` to the popper slot of the [Autocomplete](/material-ui/react-autocomplete/) component:

```jsx
<Autocomplete slotProps={{ popper: { 'data-testid': 'my-popper' } }} />
```

All additional props placed on the primary component are also propagated into the root slot (just as if they were placed in `slotProps.root`).
These two examples are equivalent:

```jsx
<Autocomplete id="badge1">
```

```jsx
<Autocomplete slotProps={{ root: { id: 'badge1' } }}>
```

:::warning
If both `slotProps.root` and additional props have the same keys but different values, the `slotProps.root` props will take precedence.

Check warning on line 88 in docs/data/material/customization/overriding-component-structure/overriding-component-structure.md

View workflow job for this annotation

GitHub Actions / runner / vale

[vale] reported by reviewdog 🐶 [Google.Will] Avoid using 'will'. Raw Output: {"message": "[Google.Will] Avoid using 'will'.", "location": {"path": "docs/data/material/customization/overriding-component-structure/overriding-component-structure.md", "range": {"start": {"line": 88, "column": 115}}}, "severity": "WARNING"}
This does not apply to classes or the `style` prop—they will be merged instead.

Check warning on line 89 in docs/data/material/customization/overriding-component-structure/overriding-component-structure.md

View workflow job for this annotation

GitHub Actions / runner / vale

[vale] reported by reviewdog 🐶 [Google.Will] Avoid using 'will'. Raw Output: {"message": "[Google.Will] Avoid using 'will'.", "location": {"path": "docs/data/material/customization/overriding-component-structure/overriding-component-structure.md", "range": {"start": {"line": 89, "column": 57}}}, "severity": "WARNING"}
:::

## Best practices

Use the `component` or `slotProps.{slot}.component` prop when you need to override the element while preserving the styles of the slot.

Use the `slots` prop when you need to replace the slot's styles and functionality with your custom component.

Overriding with `component` lets you apply the attributes of that element directly to the root.
For instance, if you override the Button's root with an `<li>` tag, you can add the `<li>` attribute `value` directly to the component.
If you did the same with `slots.root`, you would need to place this attribute on the `slotProps.root` object in order to avoid a TypeScript error.

Be mindful of your rendered DOM structure when overriding the slots of more complex components.
You can easily break the rules of semantic and accessible HTML if you deviate too far from the default structure—for instance, by unintentionally nesting block-level elements inside of inline elements.
1 change: 1 addition & 0 deletions docs/data/material/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ const pages: MuiPage[] = [
pathname: '/material-ui/customization',
children: [
{ pathname: '/material-ui/customization/how-to-customize' },
{ pathname: '/material-ui/customization/overriding-component-structure' },
{ pathname: '/material-ui/customization/dark-mode' },
{ pathname: '/material-ui/customization/color' },
{ pathname: '/material-ui/customization/right-to-left', title: 'Right-to-left' },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import * as React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import * as pageProps from 'docs/data/material/customization/overriding-component-structure/overriding-component-structure.md?muiMarkdown';

export default function Page() {
return <MarkdownDocs {...pageProps} />;
}
1 change: 1 addition & 0 deletions docs/translations/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@
"/material-ui/react-timeline": "Timeline",
"/material-ui/customization": "Customization",
"/material-ui/customization/how-to-customize": "How to customize",
"/material-ui/customization/overriding-component-structure": "Overriding component structure",
"/material-ui/customization/dark-mode": "Dark mode",
"/material-ui/customization/color": "Color",
"/material-ui/customization/right-to-left": "Right-to-left",
Expand Down
Loading