Conditional Rendering in ReactJS

Conditional Rendering in ReactJS

ยท

7 min read

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 = 'https://api.github.com/users/shamaayilahmed';
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
    fetch(url)
      .then((resp) => {
        if (resp.status >= 200 && resp.status <= 299) {    
                                               //looking for invalid users in github
          return resp.json()
        }
        setIsLoad(false);
        setIsError(true);
        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
        setIsLoad(false);
      })
      .catch((error) => console.log(error));   //catch network errors
  }, []);

  if (isLoad) {         //if data is being fetched display this
    return <div>
      <h1>loading...</h1>
    </div>;
  }
  if (isError) {         //if error occurs display this
    return <div>
      <h1>Error...</h1>
    </div>;
  }

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

export default MultipleReturns;

conditionalGIT.gif


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)}>
      Show/Hide</button> 
                           /*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 = () => {
    setSize(window.innerWidth);
  }
  useEffect(() => {
    window.addEventListener('resize', checkSize);
    return () => {
      window.removeEventListener('resize', checkSize);
    }     
//here cleanup function does a lot on the browser load by removing event 
   listener
  }, [])

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

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 ๐Ÿ™Œ

ย