Skip to content

Commit 93862e4

Browse files
committed
add note on ReactNode edge case
closes typescript-cheatsheets/react#357 thank you @pomle
1 parent 046eb68 commit 93862e4

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

docs/basic/getting-started/basic-type-examples.md

+29-2
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ export declare interface AppProps {
6060
children1: JSX.Element; // bad, doesnt account for arrays
6161
children2: JSX.Element | JSX.Element[]; // meh, doesn't accept strings
6262
children3: React.ReactChildren; // despite the name, not at all an appropriate type; it is a utility
63-
children4: React.ReactChild[]; // better
64-
children: React.ReactNode; // best, accepts everything
63+
children4: React.ReactChild[]; // better, accepts array children
64+
children: React.ReactNode; // best, accepts everything (see edge case below)
6565
functionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop type
6666
style?: React.CSSProperties; // to pass through style props
6767
onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target
@@ -71,6 +71,33 @@ export declare interface AppProps {
7171
}
7272
```
7373

74+
<details>
75+
<summary>
76+
Small `React.ReactNode` edge case
77+
</summary>
78+
79+
This code typechecks but has a runtime error:
80+
81+
```tsx
82+
83+
type Props = {
84+
children: React.ReactNode;
85+
}
86+
87+
function Comp({children}: Props) {
88+
return <div>{children}</div>;
89+
}
90+
function App() {
91+
return <Comp>{{}}</Comp> // Runtime Error: Objects not valid as React Child!
92+
}
93+
```
94+
95+
This is because `ReactNode` includes `ReactFragment` which allows a `{}` type, which is [too wide](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37596#issue-480260937). Fixing this would break a lot of libraries, so for now you just have to be mindful that `ReactNode` is not absolutely bulletproof.
96+
97+
[Thanks @pomle for raising this.](https://github.com/typescript-cheatsheets/react/issues/357)
98+
99+
</details>
100+
74101
<details>
75102
<summary><b>JSX.Element vs React.ReactNode?</b></summary>
76103

0 commit comments

Comments
 (0)