React conditional rendering

displaying content based on different situations
// updated 2025-05-15 00:05

Conditional rendering in React refers to displaying content based on some condition, giving components a more dynamic existence. Content alters depending on different situations.

We can render views using one of at least three different methods:

  • if statements
  • ternary operators
  • logical AND (&&) operators

If statements

The if statement would appear with a return statement of its own, before another final return statement:

import RenderThis from './RenderThis'
import RenderThat from './RenderThat'

// the value of this can come from anywhere or hard-coded here
const someCondition = true

function X() {
  if (someCondition) {
    return <RenderThis />
  }
  return <RenderThat />
}

function App() {
  return <X />
}

If someCondition holds true, then the first return statement will execute and ignore everything else in the block. In the example above, the "RenderThis" component would render, but "RenderThat" would not!

Ternary operators

This follows the JavaScript syntax of ternary operators:

import RenderThis from './RenderThis'
import RenderThat from './RenderThat'

// the value of this can come from anywhere or hard-coded here
const someCondition = true

function X() {
  return {someCondition ? <RenderThis /> : <RenderThat />}
}

function App() {
  return <X />
}

This way provides a more streamlined syntax, compared to using if statements!

Using logical AND (&&)

Finally, another way to do conditional rendering in React, the "logical AND" (&&) which render something if a condition holds true. If that condition did not hold true, then nothing would render:

import RenderThis from './RenderThis'
import RenderThat from './RenderThat'

// the value of this can come from anywhere or hard-coded here
const someCondition = true

function X() {
  return (
    { someCondition && <RenderThis /> }
    { !someCondition && <RenderThat /> }
  )
}

function App() {
  return <X />
}

A little less streamlined than the ternary operator, this method actually works best if we want to render something if and only if a condition holds true. Otherwise, we would not want to render anything.

⬅️ older (in textbook-react)
⚛️ React state
newer (in textbook-react) ➡️
React list rendering ⚛️
⬅️ older (in code)
⚛️ React state
newer (in code) ➡️
React list rendering ⚛️
⬅️ older (posts)
⚛️ React state
newer (posts) ➡️
React list rendering ⚛️