Skip to content

Commit

Permalink
simplify extract props docs
Browse files Browse the repository at this point in the history
closes typescript-cheatsheets/react#63 thanks to @MarcelReis' suggestions.
  • Loading branch information
alisenola authored Dec 2, 2020
1 parent 1002e42 commit 278eadc
Showing 1 changed file with 10 additions and 36 deletions.
46 changes: 10 additions & 36 deletions docs/advanced/patterns_by_usecase.md
Original file line number Diff line number Diff line change
Expand Up @@ -873,47 +873,21 @@ As you can see from the Omit example above, you can write significant logic in y

## Props: Extracting Prop Types of a Component

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

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.

```ts
import { ComponentProps, JSXElementConstructor } from "react";

// goes one step further and resolves with propTypes and defaultProps properties
type ApparentComponentProps<
C extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>
> = C extends JSXElementConstructor<infer P>
? JSX.LibraryManagedAttributes<C, P>
: ComponentProps<C>;
```

You can also use them to strongly type custom event handlers if they're not written at the call sites themselves
(i.e. inlined with the JSX attribute):
A simple solution is to use `React.ComponentProps`:

```tsx
// my-inner-component.tsx
export function MyInnerComponent(props: {
onSomeEvent(
event: ComplexEventObj,
moreArgs: ComplexArgs
): SomeWeirdReturnType;
}) {
/* ... */
}

// my-consuming-component.tsx
export function MyConsumingComponent() {
// event and moreArgs are contextually typed along with the return value
const theHandler: Props<typeof MyInnerComponent>["onSomeEvent"] = (
event,
moreArgs
) => {};
return <MyInnerComponent onSomeEvent={theHandler} />;
}
// a Modal component defined elsewhere
const defaultProps: React.ComponentProps<typeof Modal> = {
title: "Hello World",
visible: true,
onClick: jest.fn(),
};
```

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).

## Props: Render Props

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

0 comments on commit 278eadc

Please sign in to comment.