Skip to content

Commit 5d1bab6

Browse files
authored
[docs] Add generic props usage examples (#19341)
1 parent 4a96d14 commit 5d1bab6

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

docs/src/pages/guides/typescript/typescript.md

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,8 +270,43 @@ prop, this will be detailed in the component's API documentation.
270270
For example, a Button's root node can be replaced with a React Router's Link, and any additional props that are passed to Button, such as `to`, will be spread to the Link component.
271271
For a code example concerning Button and react-router-dom checkout [these demos](/guides/composition/#routing-libraries).
272272

273-
Not every component fully supports any component type you pass in. If you encounter a
274-
component that rejects its `component` props in TypeScript please open an issue.
273+
To be able to use props of such a Material-UI component on their own, props should be used with type arguments. Otherwise, the `component` prop will not be present in the props of the Material-UI component.
274+
275+
The examples below use `TypographyProps` but the same will work for any component which has props defined with `OverrideProps`.
276+
277+
The following `CustomComponent` component has the same props as the `Typography` component.
278+
279+
```ts
280+
function CustomComponent(props: TypographyProps<'a', { component: 'a' }>) {
281+
/* ... */
282+
}
283+
```
284+
285+
Now the `CustomComponent` can be used with a `component` prop which should be set to `'a'`. In addition, the `CustomComponent` will have all props of a `<a>` HTML element. The other props of the `Typography` component will also be present in props of the `CustomComponent`.
286+
287+
It is possible to have generic `CustomComponent` which will accept any React component, custom and HTML elements.
288+
289+
```ts
290+
function GenericCustomComponent<C extends React.ElementType>(
291+
props: TypographyProps<C, { component?: C }>,
292+
) {
293+
/* ... */
294+
}
295+
```
296+
297+
Now if the `GenericCustomComponent` will be used with a `component` prop provided, it should also have all props required by the provided component.
298+
299+
```ts
300+
function ThirdPartyComponent({ prop1 } : { prop1: string }) {
301+
return <div />
302+
}
303+
// ...
304+
<GenericCustomComponent component={ThirdPartyComponent} prop1="some value" />;
305+
```
306+
307+
The `prop1` became required for the `GenericCustomComponent` as the `ThirdPartyComponent` has it as a requirement.
308+
309+
Not every component fully supports any component type you pass in. If you encounter a component that rejects its `component` props in TypeScript please open an issue.
275310
There is an ongoing effort to fix this by making component props generic.
276311

277312
## Handling `value` and event handlers

0 commit comments

Comments
 (0)