You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Prevents problematic leaked values from being rendered.
27
+
Prevents bugs caused by rendering values like `0`, `NaN`, or `""` in JSX when using the `&&` operator. These values are falsy in JavaScript, but React may still attempt to render them, leading to:
28
28
29
-
Using the `&&` operator to render some element conditionally in JSX can cause unexpected values being rendered, or even crashing the rendering.
29
+
- Unexpected UI output: For example, `{0 && <div />}` renders `0` in the DOM instead of nothing.
30
+
- Crashes in React Native: Rendering `NaN`, `0`, or `""` can cause runtime crashes in versions before React 18.
30
31
31
32
## Examples
32
33
@@ -38,7 +39,7 @@ import React from "react";
38
39
function MyComponent() {
39
40
return <>{0&& <view />}</>;
40
41
// ^
41
-
// - Possible unexpected value will be rendered (React Dom: renders undesired '0', React Native: crashes 💥).
42
+
// - Possible unexpected value will be rendered (React DOM: renders undesired '0', React Native: crashes 💥).
42
43
}
43
44
```
44
45
@@ -48,7 +49,7 @@ import React from "react";
48
49
function MyComponent() {
49
50
return <>{NaN&& <div />}</>;
50
51
// ^^^
51
-
// - Possible unexpected value will be rendered (React Dom: renders undesired 'NaN', React Native: crashes 💥).
52
+
// - Possible unexpected value will be rendered (React DOM: renders undesired 'NaN', React Native: crashes 💥).
52
53
}
53
54
```
54
55
@@ -58,14 +59,15 @@ import React from "react";
58
59
function MyComponent() {
59
60
return <>{""&& <div />}</>;
60
61
// ^^
61
-
// - Possible unexpected value will be rendered (React Dom: renders nothing, React Native, with React below 18: crashes 💥).
62
+
// - Possible unexpected value will be rendered (React DOM: renders nothing, React Native, with React below 18: crashes 💥).
62
63
}
63
64
```
64
65
65
66
This can be avoided by:
66
67
67
-
- coercing the conditional to a boolean: `{!!someValue && <Something />}`
68
-
- transforming the binary expression into a ternary expression which returns null for falsy values: `{someValue ? <Something /> : null}`
68
+
- Coerce the value to a boolean: `{!!someValue && <Component />}`
69
+
- Use a ternary: `{someValue ? <Component /> : null}`
70
+
- Use comparisons: `{someValue > 0 && <Component />}`
0 commit comments