Skip to content

Commit aad23fb

Browse files
Add ComponentProps reference as first React Types example
1 parent 17f3297 commit aad23fb

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

docs/react-types/ComponentProps.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
title: ComponentProps<T>
3+
---
4+
5+
`ComponentProps<T>` is a utility type that lets you grab all valid props of an HTML or SVG element, or infer prop type for a component.
6+
7+
## Parameters
8+
9+
- `T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>`
10+
11+
`keyof JSX.IntrinsicElements` is a set of all HTML and SVG elements, such as `"div"`, `"h1"` and `"path"`.
12+
13+
`JSXElementConstructor<any>` is the type of a function or class component.
14+
15+
## Usage
16+
17+
### Getting all valid props of an HTML or SVG element
18+
19+
`ComponentProps<T>` can be used to create a type that includes all valid `div` props.
20+
21+
```tsx
22+
interface Props extends ComponentProps<"div"> {
23+
text: string;
24+
}
25+
26+
function Component({ className, children, text }: Props) {
27+
// ...
28+
}
29+
```
30+
31+
### Infer prop types from a component
32+
33+
In some cases, you might want to infer the type of a component's props.
34+
35+
```tsx
36+
interface Props {
37+
text: string;
38+
}
39+
40+
function Component(props: Props) {
41+
// ...
42+
}
43+
44+
type MyType = ComponentProps<typeof Component>;
45+
// ^? type MyType = Props
46+
```
47+
48+
The type of a specific prop can also be inferred this way. Let's say you are using an `<Icon>` component from a component library. The component takes a `name` prop that determines what icon is shown. You need to use the type of `name` in your app, but it's not made available by the library. No problem!
49+
50+
```tsx
51+
import { Icon } from "component-library";
52+
53+
type IconName = ComponentProps<typeof Icon>["name"];
54+
// ^? type IconName = "warning" | "checkmark" | ...
55+
```
56+
57+
Needless to say, `ComponentProps<T>` can be very useful!

docs/react-types/index.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
title: React Types
3+
---
4+
5+
`@types/react` makes some types available that can be very useful. Here's a list in alphabetical order with links to the detailed reference pages.
6+
7+
- [`ComponentProps<T>`](/docs/react-types/ComponentProps)

0 commit comments

Comments
 (0)