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

[material-ui] Add mergeSlotProps for extending components #44809

Merged
merged 11 commits into from
Jan 6, 2025
43 changes: 43 additions & 0 deletions docs/data/material/guides/composition/composition.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,49 @@

{{"demo": "Composition.js"}}

### Forwarding slot props

Use the `mergeSlotProps` utility function to merge custom props with the slot props.
If the arguments are functions then they'll be resolved before merging, and the result from the first argument will override the second.

Check warning on line 28 in docs/data/material/guides/composition/composition.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/guides/composition/composition.md", "range": {"start": {"line": 28, "column": 112}}}, "severity": "WARNING"}

```jsx
import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import { mergeSlotProps } from '@mui/material/utils';

export const CustomTooltip = (props: TooltipProps) => {
const { children, title, sx: sxProps } = props;

return (
<Tooltip
{...props}
title={<Box sx={{ p: 4 }}>{title}</Box>}
slotProps={{
...props.slotProps,
popper: mergeSlotProps(props.slotProps?.popper, {
className: 'custom-tooltip-popper',
disablePortal: true,
placement: 'top',
}),
}}
>
{children}
</Tooltip>
);
};
```

:::info
`className` values are concatenated rather than overriding one another.
In the snippet above, the `custom-tooltip-popper` class is applied to the Tooltip's popper slot.
If you added another `className` via the `slotProps` prop on the Custom Tooltip—as shown below—then both would be present on the rendered popper slot:

```js
<CustomTooltip slotProps={{ popper: { className: 'foo' } }} />
```

The popper slot in the original example would now have both classes applied to it, in addition to any others that may be present: `"[…] custom-tooltip-popper foo"`.
:::

## Component prop

Material UI allows you to change the root element that will be rendered via a prop called `component`.
Expand Down
1 change: 1 addition & 0 deletions packages/mui-material/src/utils/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ export { default as unsupportedProp } from './unsupportedProp';
export { default as useControlled } from './useControlled';
export { default as useEventCallback } from './useEventCallback';
export { default as useForkRef } from './useForkRef';
export { default as mergeSlotProps } from './mergeSlotProps';
export * from './types';
1 change: 1 addition & 0 deletions packages/mui-material/src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export { default as unsupportedProp } from './unsupportedProp';
export { default as useControlled } from './useControlled';
export { default as useEventCallback } from './useEventCallback';
export { default as useForkRef } from './useForkRef';
export { default as mergeSlotProps } from './mergeSlotProps';
// TODO: remove this export once ClassNameGenerator is stable
// eslint-disable-next-line @typescript-eslint/naming-convention
export const unstable_ClassNameGenerator = {
Expand Down
64 changes: 64 additions & 0 deletions packages/mui-material/src/utils/mergeSlotProps.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import * as React from 'react';
import { expectType } from '@mui/types';
import Box from '@mui/material/Box';
import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import { mergeSlotProps, SlotComponentProps } from '@mui/material/utils';

// without explicit type
const slotProps = mergeSlotProps(undefined, { className: 'foo', 'aria-label': 'bar' });
expectType<SlotComponentProps<React.ElementType, {}, {}>, typeof slotProps>(slotProps);

// explicit external slot props type
const defaultProps = mergeSlotProps<{ foo: string }>(undefined, { foo: 'bar' });
expectType<{ foo: string }, typeof defaultProps>(defaultProps);

// explicit slot props type with function
const externalSlotProps = mergeSlotProps<
(ownerState: { foo: string }) => { foo: string },
{ foo: string }
>(() => ({ foo: 'external' }), { foo: 'default' })({ foo: '' });
expectType<{ foo: string }, typeof externalSlotProps>(externalSlotProps);

export const CustomTooltip = (props: TooltipProps) => {
const { children, title } = props;

return (
<Tooltip
{...props}
title={<Box sx={{ p: 4 }}>{title}</Box>}
slotProps={{
...props.slotProps,
popper: mergeSlotProps(props.slotProps?.popper, {
className: 'custom-tooltip',
disablePortal: true,
placement: 'top',
}),
}}
>
{children}
</Tooltip>
);
};

export const CustomTooltip2 = (props: TooltipProps) => {
const { children, title } = props;

// to ensure that the return type of `mergeSlotProps` is correctly inferred
const popperProps = mergeSlotProps(props.slotProps?.popper, {
className: 'custom-tooltip',
disablePortal: true,
placement: 'top',
});
return (
<Tooltip
{...props}
title={<Box sx={{ p: 4 }}>{title}</Box>}
slotProps={{
...props.slotProps,
popper: popperProps,
}}
>
{children}
</Tooltip>
);
};
99 changes: 99 additions & 0 deletions packages/mui-material/src/utils/mergeSlotProps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { expect } from 'chai';

import mergeSlotProps from './mergeSlotProps';

type OwnerState = {
className: string;
'aria-label'?: string;
};

describe('utils/index.js', () => {
describe('mergeSlotProps', () => {
it('external slot props is undefined', () => {
expect(
mergeSlotProps<OwnerState>(undefined, {
className: 'default',
'aria-label': 'foo',
}),
).to.deep.equal({
className: 'default',
'aria-label': 'foo',
});
});

it('external slot props should override', () => {
expect(
mergeSlotProps<OwnerState>(
{ className: 'external', 'aria-label': 'bar' },
{ className: 'default', 'aria-label': 'foo' },
),
).to.deep.equal({
className: 'default external',
'aria-label': 'bar',
});
});

it('external slot props is a function', () => {
expect(
mergeSlotProps<(ownerState: OwnerState) => OwnerState, OwnerState>(
() => ({
className: 'external',
}),
{ className: 'default', 'aria-label': 'foo' },
)({ className: '' }),
).to.deep.equal({
className: 'default external',
'aria-label': 'foo',
});
});

it('default slot props is a function', () => {
expect(
mergeSlotProps<OwnerState, (ownerState: OwnerState) => OwnerState>(
{
className: 'external',
},
() => ({ className: 'default', 'aria-label': 'foo' }),
)({ className: 'base' }),
).to.deep.equal({
className: 'base default external',
'aria-label': 'foo',
});
});

it('both slot props are functions', () => {
expect(
mergeSlotProps<(ownerState: OwnerState) => OwnerState>(
() => ({
className: 'external',
}),
() => ({
className: 'default',
'aria-label': 'foo',
}),
)({ className: 'base' }),
).to.deep.equal({
className: 'base default external',
'aria-label': 'foo',
});
});

it('external callback should be called with default slot props', () => {
expect(
mergeSlotProps<(ownerState: OwnerState) => OwnerState>(
({ 'aria-label': ariaLabel }) => ({
className: 'external',
'aria-label': ariaLabel === 'foo' ? 'bar' : 'baz',
}),
() => ({
className: 'default',
'aria-label': 'foo',
}),
)({ className: 'base', 'aria-label': 'unknown' }),
).to.deep.equal({
className: 'base default external',
'aria-label': 'bar',
});
});
});
});
43 changes: 43 additions & 0 deletions packages/mui-material/src/utils/mergeSlotProps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { SlotComponentProps } from '@mui/utils';
import clsx from 'clsx';

export default function mergeSlotProps<
T extends SlotComponentProps<React.ElementType, {}, {}>,
K = T,
// infer external slot props first to provide autocomplete for default slot props
U = T extends Function ? T : K extends Function ? K : T extends undefined ? K : T,
>(externalSlotProps: T | undefined, defaultSlotProps: K): U {
if (!externalSlotProps) {
return defaultSlotProps as unknown as U;
}
if (typeof externalSlotProps === 'function' || typeof defaultSlotProps === 'function') {
return ((ownerState: Record<string, any>) => {
const defaultSlotPropsValue =
typeof defaultSlotProps === 'function' ? defaultSlotProps(ownerState) : defaultSlotProps;
const externalSlotPropsValue =
typeof externalSlotProps === 'function'
? externalSlotProps({ ...ownerState, ...defaultSlotPropsValue })
DiegoAndai marked this conversation as resolved.
Show resolved Hide resolved
: externalSlotProps;

const className = clsx(
ownerState?.className,
defaultSlotPropsValue?.className,
externalSlotPropsValue?.className,
);
return {
...defaultSlotPropsValue,
...externalSlotPropsValue,
...(!!className && { className }),
};
}) as U;
}
const className = clsx(
(defaultSlotProps as Record<string, any>)?.className,
externalSlotProps?.className,
);
return {
...defaultSlotProps,
...externalSlotProps,
...(!!className && { className }),
} as U;
}
Loading