React native and falsy values: a common gotcha
When developing mobile applications with React Native, web developers experienced in React often encounter unexpected behavior with conditional rendering and empty strings. A pattern that works flawlessly in React for web can cause runtime errors in React Native.
The Problem
This common React pattern fails in React Native when message
is an empty string:
{message && <Text>{message}</Text>}
The code above throws the following error:
Unexpected text node: . A text node cannot be a child of a <View>.
Why This Happens
The issue stems from how JavaScript handles falsy values in conditional expressions and how React Native processes text nodes:
- In JavaScript, an empty string is falsy
- When evaluating
message && <Text>{message}</Text>
, if message is an empty string:- The expression short-circuits and returns the empty string
- React Native tries to render this empty string as a text node
- Unlike React web, React Native doesn't allow raw text nodes as children of
<View>
components
The Solution
Always explicitly convert potentially falsy values to Boolean when using this pattern:
{Boolean(message) && <Text>{message}</Text>}
This works because:
Boolean("")
converts the empty string tofalse;
- React Native properly handles
false
in JSX, rendering nothing; - No text node is created, so no error occurs;
Alternative Approaches
You can also use the ternary operator, which might be more explicit:
{message ? <Text>{message}</Text> : null}
Best Practice
When working with React Native, always be explicit about type conversion in conditional rendering. While the original pattern works in React web, maintaining consistent use of Boolean() conversion helps prevent these subtle runtime errors and makes the code more maintainable across platforms.
Remember: React Native's handling of text nodes is stricter than React web, so patterns that work in web applications might need adjustment for mobile development.