You should know them, to master Conditional Rendering in React

conditional rendering simply means “ render elements based on a condition ”,

narendrapalacharla
3 min readOct 14, 2021
Reaction after reading this article 😐

When we are building webpages on React, We don’t always want to render everything to our webpage. Based on a certain condition, we might want to hide/show the elements/components. This is nothing but conditional rendering.

Most developers are familiar with if and ternary operators for conditional rendering the components in the react, there are few other ways to do it, let us have a deep dive into all the ways.

  • if
  • ternary operator
  • inline-logical && operator
  • switch case operator
  • Conditional Rendering with enums

First, let us know our traditional if and ternary operators for the conditional rendering in a bit of detail.

if

if the conditional rendering is with the ‘if’ statement then the component/element return only the condition is true or else the component/element in the ‘else’ statement will be rendered. the below example will help you to understand.

if-else … condition implemented inside the Condition component in the below code snippet.

If Statement in rendering

ternary operator

the ternary operator is used in cases where two blocks alternate given a certain condition. the syntax for the ternary operator is “condition? true: false”. the ternary operator is inside the render function of the Update class component in the below code snippet.

Ternary operator to render the react components

inline-logical && operator

If the condition is true, it will return the element right after &&, and if it is false, React will ignore and skip it. inline logic is implemented inside the render function.

Inline if logic && operator to render the react components

switch case operator

In the switch case, conditional rendering is applied based on a different state. which makes multiple conditional renderings possible.

Switch case operator to render the react components

enums

enums are a better version in multiple conditioning render compared to the switch case operator in terms of readability of code, It is perfect for mapping between different state.

Enums to render the react components

EnumState child component receives “this.state.number” as a prop’s from the parent UpdateFour class component which will return the div element, the element value can be received from the ENUM_STATES object in which all the states for conditional rendering are available.

All the above code snippets create the same output, initially, the screen will show “iam number 2”, if you click on the button “change the state”, it will hide the previous element and display the “you are number 1”.

Conditional rendering output

--

--