Skip to main content

Command Palette

Search for a command to run...

Conditional Rendering in React/React Native — Examples

Real-world examples of conditional rendering techniques in React and React Native, with tips on avoiding common pitfalls.

Published
4 min read
Conditional Rendering in React/React Native — Examples

Originally written in 2023. Content may vary slightly across newer versions.

This article is part of a series that document my first react native project. They encompass a variety of topics, and come in different shapes and flavours — some are hands-on notes, some are best practices (learn-and-think products by me), and some are an endeavour to get an in-depth understanding of the underlying mechanisms of how React / React Native works.

It is almost impossible not to use conditional rendering in a React / React Native app. Therefore, it is crucial for developers to understand the different scenarios in which conditional rendering is required and which kind of conditional rendering is most appropriate for the current situation.

The fundamentals — Part 1

Let's go over some fundamental knowledge about rendering in JSX. According to the React docs on JSX in depth, JSX expressions include Booleans, Null, and Undefined are ignored during rendering — they simply don't render.

Therefore, we are clear on the fact that if we want to conditionally render a component or for a component to skip rendering, we need to think about returning one of the above mentioned values instead.

The fundamentals — Part 2

There is a whole section dedicated to conditional rendering in the React docs, so I'd like to skip the reinventing-the-wheel play, and give you a few minutes to refresh your memory by quickly skimming through it.

I will go over each conditional rendering technique with a real-project-example and explains why a specific technique is suitable for the current situation.

Use Logical AND operator (&&)

Before jumping into the hands-on part, I’d like to say I'm very much inspired by Dana Janoskova in her article about how to write clean JSX and components. She talks about the approach to figure out which props are required and which are not. The basic idea is that you need to think about this question: what does this component do? And which props are necessary for the rendering of this component. In other words, without this prop / piece of data, the existence of this component is meaningless.

Equipped with this mindset, I set out to think about the purpose of the LocationItem component. This component is a modal that contains the detailed information about a certain location. When the user clicks on a LocationMarker component, this modal will show. So the most important part of this component or prop is the location prop.

In here, I want to use && operator because 1. isShowItem and !_isEmpty(location) both are required to be satisfied to render the LocationItem; 2. if both return true, then the LocationItem renders. If not, the expression returns false, which is also fine and renders nothing.

However, there is a pitfall you might want to pay attention to (because I did not so I’m writing this piece to remind myself not to repeat it). Avoid using empty strings or 0 in the conditions. Otherwise, it renders the empty strings or 0 !! And if you came across this, it throws an error: put text inside <Text />.

import React, { useState, useCallback } from 'react'
import _ from 'lodash'
import { Marker } from 'react-native-maps'

import LocationItem from 'Locations/LocationItem'
import styles from './styles'

const LocationMarker = ({ latitude, longitude, location }) => {
  const [isShowItem, setIsShowItem] = useState(false)
  
  const handleMarkerPress = useCallback(() => setIsShowItem(true))
  
  return (
    <Marker coordinate={{ latitude, longitude }} onPress={handleMarkerPress}>
    {isShowItem && !_.isEmpty(location) && (
      <LocationItem
        isShowItem={isShowItem}
        setIsShowItem={setIsShowItem}
        location={location}
      />
    )}
    </Marker>
  )
}

Use If to conditionally returning JSX

If this component needs to go into loading before rendering, it is more suitable to use if to conditionally returning JSX and avoid nesting at the same time (also inspired by Dana).

import React, { useState, useCallback } from 'react'
import _ from 'lodash'
import { Marker } from 'react-native-maps'

import LocationItem from 'Locations/LocationItem'
import styles from './styles'

const LocationMarker = ({ latitude, longitude, location }) => {
  const [isShowItem, setIsShowItem] = useState(false)
  
  const handleMarkerPress = useCallback(() => setIsShowItem(true))
  
  if (!longitude || !latitude) {
    return null
  }
  
  return (
    <Marker coordinate={{ latitude, longitude }} onPress={handleMarkerPress}>
    {isShowItem && !_.isEmpty(location) && (
      <LocationItem
        isShowItem={isShowItem}
        setIsShowItem={setIsShowItem}
        location={location}
      />
    )}
    </Marker>
  )
}

Using the same example as before, I only added the if condition for longitude & latitude. This component only needs to render if it has valid longitude and latitude values.

To sum up, conditional rendering is a must if you are developing using React or React Native. Hope a few tips can help you a long way!