Skip to content
This repository was archived by the owner on Nov 8, 2024. It is now read-only.

Commit d7a1201

Browse files
add React Generics example
1 parent 6e2b7f7 commit d7a1201

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

frontend/Typed_React_Guidelines.md

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
- Props declaration
22
```typescript
3-
const upgradeCTA = ({ label }: { label?: string}) : React.ReactNode =>
4-
// Theoretically we could skip the type definition in this case
5-
// as it will be infered from the default values
3+
const upgradeCTA = ({ label = 'upgrade' }: { label?: string}) : React.Element =>
64
```
75
- useful React props types ([ref](https://github.com/typescript-cheatsheets/react#useful-react-prop-type-examples).)
86
```typescript
97
export declare interface AppProps {
10-
children: React.ReactNode; // best, accepts everything (see edge case below)
8+
children: React.ReactNode;
119
functionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop type
1210
style?: React.CSSProperties; // to pass through style props
1311
onChange?: React.FormEvent<HTMLInputElement>; // form events! the generic parameter is the type of event.target
@@ -35,3 +33,23 @@
3533
//To fix it, you need to specify the Type of the prop
3634
margin: 2px 0 ${({ content } : { content: Detail }) => content.images ? '24px' : '0px'} 0;
3735
```
36+
37+
- Generics
38+
```typescript
39+
import React, { useState } from 'react'
40+
41+
// For props
42+
interface WithName {
43+
name: string|null;
44+
}
45+
46+
const Foo: React.FC<WithName> = ({ name }) => {
47+
return <div>{name}</div>
48+
}
49+
50+
// To strongly type hooks
51+
const Bar: React.FC = () => {
52+
const [state, setState] = useState<WithName>({ name: 'bar' })
53+
return <div>{state.name}</div>
54+
}
55+
```

0 commit comments

Comments
 (0)