Skip to content

Commit 427ff7b

Browse files
committed
Add HOCs page
1 parent e845537 commit 427ff7b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/pages/examples/hocs.mdx

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
---
2+
name: Higher Order Components (HOCs)
3+
route: /examples/hocs
4+
menu: Examples
5+
---
6+
7+
# Higher Order Components (HOCs)
8+
9+
Please note that this section uses the `utility-types` [package](https://github.com/piotrwitek/utility-types) since, as of May 2019, the helper functions were unavailable in TypeScript.
10+
11+
## Injected Props
12+
13+
HOCs often inject props into wrapped components. In the below example, `T` is defined as the `WrappedComponent` props together with the
14+
15+
```tsx
16+
import { ComponentType } from 'react';
17+
import { Diff } from 'utility-types';
18+
19+
export interface WithWoofStringProps {
20+
woof: string;
21+
}
22+
23+
export default function withWoofString<T extends WithWoofStringProps>(
24+
WrappedComponent: ComponentType<T>
25+
) {
26+
const woof = 'woof';
27+
28+
// note below that Diff removes the props from T that exist in WithWoofStringProps
29+
// this leaves us with the props of the originally passed in component (without the injected props)
30+
const hocComponent = (props: Diff<T, WithWoofStringProps>) => (
31+
<WrappedComponent {...props as T} woof={woof} />
32+
);
33+
return hocComponent;
34+
}
35+
```

0 commit comments

Comments
 (0)