Skip to content

Commit 1cde32b

Browse files
author
chef1119
committed
simplify extract props docs
closes typescript-cheatsheets/react#63 thanks to @MarcelReis' suggestions.
1 parent 26612ce commit 1cde32b

File tree

1 file changed

+10
-36
lines changed

1 file changed

+10
-36
lines changed

docs/advanced/patterns_by_usecase.md

+10-36
Original file line numberDiff line numberDiff line change
@@ -873,47 +873,21 @@ As you can see from the Omit example above, you can write significant logic in y
873873

874874
## Props: Extracting Prop Types of a Component
875875

876-
There are a lot of places where you want to reuse some slices of props because of prop drilling,
877-
so you can either export the props type as part of the module or extract them (either way works).
876+
Sometimes you want the prop types of a component, but it isn't exported.
878877

879-
The advantage of extracting the prop types is that you won't need to export everything, and a refactor of the source of truth component will propagate to all consuming components.
880-
881-
```ts
882-
import { ComponentProps, JSXElementConstructor } from "react";
883-
884-
// goes one step further and resolves with propTypes and defaultProps properties
885-
type ApparentComponentProps<
886-
C extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>
887-
> = C extends JSXElementConstructor<infer P>
888-
? JSX.LibraryManagedAttributes<C, P>
889-
: ComponentProps<C>;
890-
```
891-
892-
You can also use them to strongly type custom event handlers if they're not written at the call sites themselves
893-
(i.e. inlined with the JSX attribute):
878+
A simple solution is to use `React.ComponentProps`:
894879

895880
```tsx
896-
// my-inner-component.tsx
897-
export function MyInnerComponent(props: {
898-
onSomeEvent(
899-
event: ComplexEventObj,
900-
moreArgs: ComplexArgs
901-
): SomeWeirdReturnType;
902-
}) {
903-
/* ... */
904-
}
905-
906-
// my-consuming-component.tsx
907-
export function MyConsumingComponent() {
908-
// event and moreArgs are contextually typed along with the return value
909-
const theHandler: Props<typeof MyInnerComponent>["onSomeEvent"] = (
910-
event,
911-
moreArgs
912-
) => {};
913-
return <MyInnerComponent onSomeEvent={theHandler} />;
914-
}
881+
// a Modal component defined elsewhere
882+
const defaultProps: React.ComponentProps<typeof Modal> = {
883+
title: "Hello World",
884+
visible: true,
885+
onClick: jest.fn(),
886+
};
915887
```
916888

889+
There are advanced edge cases if you want to extract the prop types of a component taking into account internal props, `propTypes`, and `defaultProps` - [check our issue here for helper utilities that resolve these](https://github.com/typescript-cheatsheets/react/issues/63).
890+
917891
## Props: Render Props
918892

919893
> Advice: Where possible, you should try to use Hooks instead of Render Props. We include this merely for completeness.

0 commit comments

Comments
 (0)