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

[TablePagination] Drop component prop #37059

Merged
merged 11 commits into from
Apr 28, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
39 changes: 23 additions & 16 deletions docs/data/base/components/table-pagination/table-pagination.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ It controls two properties of its parent table:
- number of rows per page

Table Pagination renders its internal elements in a `<td>` tag by default so it can be inserted into a table's `<tr>`.
You can use the `component` or `slots.root` prop to render a different root element—for example, if you need to place the pagination controls outside of the table.
You can use the `slots.root` prop to render a different root element—for example, if you need to place the pagination controls outside of the table.
See the [Slot props section](#slot-props) for details.

{{"demo": "UnstyledPaginationIntroduction.js", "defaultCodeOpen": false, "bg": "gradient"}}
Expand Down Expand Up @@ -99,27 +99,17 @@ The Table Pagination component is composed of a root `<td>` that houses up to te
</td>
```

### Slot props
### Custom structure

:::info
The following props are available on all non-utility Base components.
See [Usage](/base/getting-started/usage/) for full details.
:::

Use the `component` prop to override the root slot with a custom element:

```jsx
<TablePagination component="div" />
```

Use the `slots` prop to override any interior slots in addition to the root:
Use the `slots` prop to override the root or any other interior slot:

```jsx
<TablePagination slots={{ root: 'div', toolbar: 'nav' }} />
```

:::warning
If the root element is customized with both the `component` and `slots` props, then `component` will take precedence.
:::info
The `slots` prop is available on all non-utility Base components.
See [Overriding component structure](/base/guides/overriding-component-structure/) for full details.
:::

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:::info
The `slots` prop is available on all non-utility Base components.
See [Overriding component structure](/base/guides/overriding-component-structure/) for full details.

Use the `slotProps` prop to pass custom props to internal slots.
Expand All @@ -131,6 +121,23 @@ The following code snippet applies a CSS class called `my-spacer` to the spacer

## Customization

### Usage with TypeScript

In TypeScript, you can specify the custom component type used in the `slots.root` as a generic parameter of the unstyled component. This way, you can safely provide the custom root's props directly on the component:

```tsx
<TablePagination<typeof CustomComponent>
slots={{ root: CustomComponent }}
customProp
/>
```

The same applies for props specific to custom primitive elements:

```tsx
<TablePagination<'button'> slots={{ root: 'button' }} onClick={() => {}} />
```

### Custom pagination options

You can customize the options shown in the **Rows per page** select using the `rowsPerPageOptions` prop.
Expand Down
1 change: 0 additions & 1 deletion docs/pages/base/api/table-pagination.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"onPageChange": { "type": { "name": "func" }, "required": true },
"page": { "type": { "name": "custom", "description": "integer" }, "required": true },
"rowsPerPage": { "type": { "name": "custom", "description": "integer" }, "required": true },
"component": { "type": { "name": "elementType" } },
"getItemAriaLabel": {
"type": { "name": "func" },
"default": "function defaultGetAriaLabel(type: ItemAriaLabelType) {\n return `Go to ${type} page`;\n}"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"componentDescription": "A pagination for tables.",
"propDescriptions": {
"component": "The component used for the root node. Either a string to use a HTML element or a component.",
"count": "The total number of rows.<br>To enable server side pagination for an unknown number of items, provide -1.",
"getItemAriaLabel": "Accepts a function which returns a string value that provides a user-friendly name for the current page. This is important for screen reader users.<br>For localization purposes, you can use the provided <a href=\"/material-ui/guides/localization/\">translations</a>.<br><br><strong>Signature:</strong><br><code>function(type: string) =&gt; string</code><br><em>type:</em> The link or button type to format (&#39;first&#39; | &#39;last&#39; | &#39;next&#39; | &#39;previous&#39;).",
"labelDisplayedRows": "Customize the displayed rows label. Invoked with a <code>{ from, to, count, page }</code> object.<br>For localization purposes, you can use the provided <a href=\"/material-ui/guides/localization/\">translations</a>.",
Expand Down
57 changes: 57 additions & 0 deletions packages/mui-base/src/TablePagination/TablePagination.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import TablePagination from '@mui/base/TablePagination';
import { expectType } from '@mui/types';
import {
TablePaginationActionsSlotProps,
TablePaginationDisplayedRowsSlotProps,
Expand Down Expand Up @@ -75,3 +76,59 @@ const styledTablePagination = (
}}
/>
);

const polymorphicComponentTest = () => {
const CustomComponent: React.FC<{ stringProp: string; numberProp: number }> =
function CustomComponent() {
return <div />;
};

const requiredProps = {
count: 10,
getItemAriaLabel: () => '',
onPageChange: () => {},
page: 0,
rowsPerPage: 10,
showFirstButton: true,
showLastButton: true,
};

return (
<div>
{/* @ts-expect-error */}
<TablePagination {...requiredProps} invalidProp={0} />

<TablePagination<'a'> {...requiredProps} slots={{ root: 'a' }} href="#" />

<TablePagination<typeof CustomComponent>
{...requiredProps}
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<TablePagination<typeof CustomComponent>
{...requiredProps}
slots={{ root: CustomComponent }}
/>

<TablePagination<'button'>
{...requiredProps}
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>

<TablePagination<'button'>
{...requiredProps}
slots={{ root: 'button' }}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
onMouseDown={(e) => {
expectType<React.MouseEvent<HTMLButtonElement, MouseEvent>, typeof e>(e);
e.currentTarget.checkValidity();
}}
/>
</div>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ describe('<TablePagination />', () => {
testWithElement: 'th',
},
},
skip: ['componentProp'],
}),
);

Expand Down
21 changes: 5 additions & 16 deletions packages/mui-base/src/TablePagination/TablePagination.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import * as React from 'react';
import PropTypes from 'prop-types';
import { unstable_useId as useId, chainPropTypes, integerPropType } from '@mui/utils';
import { OverridableComponent } from '@mui/types';
import { useSlotProps, WithOptionalOwnerState } from '../utils';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import composeClasses from '../composeClasses';
import isHostComponent from '../utils/isHostComponent';
import TablePaginationActions from './TablePaginationActions';
Expand Down Expand Up @@ -63,7 +62,6 @@ const TablePagination = React.forwardRef(function TablePagination<
RootComponentType extends React.ElementType,
>(props: TablePaginationProps<RootComponentType>, forwardedRef: React.ForwardedRef<Element>) {
const {
component,
colSpan: colSpanProp,
count,
getItemAriaLabel = defaultGetAriaLabel,
Expand All @@ -85,7 +83,8 @@ const TablePagination = React.forwardRef(function TablePagination<
const classes = useUtilityClasses();

let colSpan;
if (!component || component === 'td' || !isHostComponent(component)) {
const Root = slots.root ?? 'td';
if (Root === 'td' || !isHostComponent(Root)) {
colSpan = colSpanProp || 1000; // col-span over everything
}

Expand All @@ -99,7 +98,6 @@ const TablePagination = React.forwardRef(function TablePagination<
const selectId = useId(selectIdProp);
const labelId = useId(labelIdProp);

const Root = component ?? slots.root ?? 'td';
const rootProps: WithOptionalOwnerState<TablePaginationRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
Expand Down Expand Up @@ -237,26 +235,17 @@ const TablePagination = React.forwardRef(function TablePagination<
</Toolbar>
</Root>
);
}) as OverridableComponent<TablePaginationTypeMap>;
}) as PolymorphicComponent<TablePaginationTypeMap>;

TablePagination.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
children: PropTypes.node,
/**
* @ignore
*/
colSpan: PropTypes.number,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* The total number of rows.
*
Expand Down Expand Up @@ -357,7 +346,7 @@ TablePagination.propTypes /* remove-proptypes */ = {
* The props used for each slot inside the TablePagination.
* @default {}
*/
slotProps: PropTypes.shape({
slotProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({
actions: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
displayedRows: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
menuItem: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as React from 'react';
import { OverrideProps } from '@mui/types';
import { SlotComponentProps } from '../utils';
import { PolymorphicProps, SlotComponentProps } from '../utils';
import TablePaginationActions from './TablePaginationActions';
import { ItemAriaLabelType } from './common.types';

Expand Down Expand Up @@ -205,9 +204,7 @@ export interface TablePaginationTypeMap<

export type TablePaginationProps<
RootComponentType extends React.ElementType = TablePaginationTypeMap['defaultComponent'],
> = OverrideProps<TablePaginationTypeMap<{}, RootComponentType>, RootComponentType> & {
component?: RootComponentType;
};
> = PolymorphicProps<TablePaginationTypeMap<{}, RootComponentType>, RootComponentType>;

export type TablePaginationOwnerState = TablePaginationOwnProps;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,26 +56,29 @@ const polymorphicComponentTest = () => {
{/* @ts-expect-error */}
<TablePaginationActions {...requiredProps} invalidProp={0} />

<TablePaginationActions {...requiredProps} component="a" href="#" />
<TablePaginationActions<'a'> {...requiredProps} slots={{ root: 'a' }} href="#" />

<TablePaginationActions
<TablePaginationActions<typeof CustomComponent>
{...requiredProps}
component={CustomComponent}
slots={{ root: CustomComponent }}
stringProp="test"
numberProp={0}
/>
{/* @ts-expect-error */}
<TablePaginationActions {...requiredProps} component={CustomComponent} />
<TablePaginationActions<typeof CustomComponent>
{...requiredProps}
slots={{ root: CustomComponent }}
/>

<TablePaginationActions
{...requiredProps}
component="button"
slots={{ root: 'button' }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.checkValidity()}
/>

<TablePaginationActions<'button'>
{...requiredProps}
component="button"
slots={{ root: 'button' }}
ref={(elem) => {
expectType<HTMLButtonElement | null, typeof elem>(elem);
}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as React from 'react';
import { OverridableComponent } from '@mui/types';
import { useSlotProps, WithOptionalOwnerState } from '../utils';
import { PolymorphicComponent, useSlotProps, WithOptionalOwnerState } from '../utils';
import {
TablePaginationActionsButtonSlotProps,
TablePaginationActionsProps,
Expand Down Expand Up @@ -36,7 +35,6 @@ const TablePaginationActions = React.forwardRef(function TablePaginationActions<
forwardedRef: React.ForwardedRef<Element>,
) {
const {
component,
count,
getItemAriaLabel = defaultGetAriaLabel,
onPageChange,
Expand Down Expand Up @@ -70,7 +68,7 @@ const TablePaginationActions = React.forwardRef(function TablePaginationActions<
onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
};

const Root = slots.root ?? component ?? 'div';
const Root = slots.root ?? 'div';
const rootProps: WithOptionalOwnerState<TablePaginationActionsRootSlotProps> = useSlotProps({
elementType: Root,
externalSlotProps: slotProps.root,
Expand Down Expand Up @@ -160,6 +158,6 @@ const TablePaginationActions = React.forwardRef(function TablePaginationActions<
)}
</Root>
);
}) as OverridableComponent<TablePaginationActionsTypeMap>;
}) as PolymorphicComponent<TablePaginationActionsTypeMap>;

export default TablePaginationActions;
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as React from 'react';
import { OverrideProps } from '@mui/types';
import { SlotComponentProps } from '../utils';
import { PolymorphicProps, SlotComponentProps } from '../utils';

export interface TablePaginationActionsRootSlotPropsOverrides {}
export interface TablePaginationActionsFirstButtonSlotPropsOverrides {}
Expand Down Expand Up @@ -118,9 +117,7 @@ export interface TablePaginationActionsSlots {

export type TablePaginationActionsProps<
RootComponentType extends React.ElementType = TablePaginationActionsTypeMap['defaultComponent'],
> = OverrideProps<TablePaginationActionsTypeMap<{}, RootComponentType>, RootComponentType> & {
component?: RootComponentType;
};
> = PolymorphicProps<TablePaginationActionsTypeMap<{}, RootComponentType>, RootComponentType>;

export interface TablePaginationActionsTypeMap<
AdditionalProps = {},
Expand Down