Shamaayil Ahmed
Shamaayil Ahmed


Shamaayil Ahmed

Conditional Rendering in ReactJS

Conditional Rendering in ReactJS

Shamaayil Ahmed's photo
Shamaayil Ahmed
ยทDec 16, 2020ยท

7 min read

Play this article

Let's head on to the fascinating stuff conditional rendering in reactJS, and explain some of the most common use cases that you may come across your work.

Conditional Rendering ๐Ÿค”

Let's break the word for now and look into it, As conditional is similar to the conditional statements that we have known so far (if, if else, else if) and so on. Rendering can be more of a react stuff were the react components are transformed to DOM nodes that are displayed on screen.

So collaboratively according to the state values and the conditions provided react renders the component.

Then we can have different components for different state values as well, so this can be understood as a UI/UX best practice for pleasing and meaningful interactions with the software.

Manipulating state values using conditionals can be thought as,

const [error,isError]=useState(false);

if(error){                         //for some reason if error occurs
   return <h2>Error occurred !!</h2>
return <h2>Conditional Rendering</h2>   //if there is no error

Use Cases โ„น

There may be like plenty of use cases that you may come across whilst developing, as far the post is concerned let's explain some of them.

  1. Multiple Returns
  2. Short Circuit Evaluation and Ternary Operators
  3. Show/Hide Components

Let's dive into each of 'em:

Multiple Returns

This is somewhat similar to our explanations so far, for different state values different components appears. We keep manipulating the state value for the dynamicity of the UI.

Let's look on an interesting application of fetching data and displaying the contents.

import React, { useState, useEffect } from 'react';
const url = '';
const MultipleReturns = () => {         //component to be rendered elsewhere
  const [isLoad, setIsLoad] = useState(true);     //for loading component
  const [isError, setIsError] = useState(false);    //for error component
  const [user, setUser] = useState({ name: 'default user', image: '', bio: '' });
                    //for storing the data
  useEffect(() => {           //fetch purpose
      .then((resp) => {
        if (resp.status >= 200 && resp.status <= 299) {    
                                               //looking for invalid users in github
          return resp.json()
        throw new Error(resp.statusText);
      .then((user) => {
        const { login, avatar_url, bio } = user;     //destructuring data required
        setUser({ ...user, name: { login }, image: { avatar_url }, info: { bio } });  
                                              //passing the data to user object
      .catch((error) => console.log(error));   //catch network errors
  }, []);

  if (isLoad) {         //if data is being fetched display this
    return <div>
  if (isError) {         //if error occurs display this
    return <div>

  const { login, avatar_url, bio } = user;    //if fetching is done display the data
  return <>
    <hr />
    <img src={avatar_url} alt={login} />

export default MultipleReturns;


Short Circuit Evaluation and Ternary Operators

Since at the end of the day react is just JavaScript with power as well the return value of react is always JavaScript.

So without use of any createElement() or appendChild() we can return pure html from conmponents which is also called JSX(Syntax Extension to JavaScript).

JSX has to definitely return an expression so far the conditional rendering we are dealing with JSX can't interpret or include any conditions, here the short-circuit analysis comes into action

Let's see a simple use case;

import React, { useState } from 'react';

const ShortCircuit = () => {
  const [text, setText] = useState('');
  const [isError, setIsError] = useState(false);

  return <>
    <h1>{text || 'Shamaayil'}</h1> //return the name if either are true or avail
    <button className='btn' onClick={() => setIsError(!isError)}>Toggle error</button>       //the moment its clicked alter the state value
    {isError && <h1>Error...</h1>}
    {isError ? <p>there is an error..</p> : <p>no error..</p>}
                              //if there is error display error else display no error

export default ShortCircuit;

Show/Hide Components

More of the toggling state value in JSX is used to show/hide components which give a dynamic look to the UI.

Let's see an interesting snippet which show/hide your screen width.

import React, { useState, useEffect } from 'react';

const ShowHide = () => {
  const [show, setShow] = useState(false);
  return <>
    <button className='btn' 
        onClick={() => setShow(!show)}>
                           /*toggling button for show/hide*/
    {show && <Item />}  
               /*if state value show is true the component is displayed*/

const Item = () => {
  const [size, setSize] = useState(window.innerWidth);

  const checkSize = () => {
  useEffect(() => {
    window.addEventListener('resize', checkSize);
    return () => {
      window.removeEventListener('resize', checkSize);
//here cleanup function does a lot on the browser load by removing event 
  }, [])

  return <div style={{ marginTop: '2rem' }}>
    <h2>Size: {size} PX</h2>

export default ShowHide;

Major Takeaway

Rendering react components can be conditional according to the state value of the specified component.

Let's connect

Social Links

Hope you all liked the post, share your impressions and queries below ๐Ÿ™Œ

Share this