I’ve been developing with react native for a couple of years now. Along the way I’ve encountered numerous little quirks to the development process that you get used to. These include some best practices, as well as “no better option” practices, but there’s one matter I consistently find myself commenting on in pull requests that I’d like to share with you.
BAD: Conditionally rendering text with the && operator.
In the snippet above, we have a component conditionally rendering based on the “truthiness” of its string value contents,
potentialTextValue. This is a common React pattern and is perfectly fine. The problem however, is that in React Native, rendering a string, even an empty one, outside of a component is bad news. If you’re familiar with the
&& operator, then you know when
potentialTextValue === '', the expression in the snippet will evaluate to
''. Boom, we just crashed our app 💥.
Ok, this all makes sense, “so what is the big deal?”, you ask me. If our logic was going to lead to an app crash, then surely we’d see this in development. Well, maybe. The problem is that depending on your react native package version, this may not actually crash iOS. If you have someone primarily developing on iOS, they could easily write this code and everything would seem fine, only to fire up the Android build and see it crash.
(NOTE: as of the writing of this
react-native: "0.57.8" will correctly crash when evaluating an empty string outside of a
Text component on iOS. This issue primarily affects users still on react native
0.56 and below.)
If you want to be safe, make these two small tweaks to protect your conditional renders:
You can easily use type coercion or a ternary to be more explicit about the fallback return value, circumventing the issue entirely. This is the small suggestion I find myself making in pull requests. As I mentioned, if you’re on react-native
57 or greater, you will likely catch this before it becomes an issue, but for everyone on an older RN version, I find this is surprisingly common in pull requests.