What is short circuit condition? and how works in React

Hi, in this post I’m going to show you what is the short circuit condition and also you will learn how this conditional is applied in a React example.

The short circuit condition is very useful in react when we are trying to render some component or some HTML in our application, let suppose that we need to render (print some html in the browser) a list of friends every time that I click a button, so this is my button:

By default the list is hidden and after I click the button the list will be showing like this:

Note: also check how the button text is changing when I clicked the button.

Ok, A simple way to show or hide elements on a react application is implement the “short circuit condition” where the syntax is this:

{ condition && (Html or subcomponents to render) }

So, the condition needs to be fulfilled in order to render the html or subcomponent.

Example:

In this next example the condition is evaluated like this:

This const called ‘show’ have a false value?

YES is a false value – > Then rendering!

NO is not a false value -> Don’t rendering.

// The value is false
const show = false;

// The condition is evaluated
{ !show && (<h1>I am rendering in the browser<h1> }

Ok, let see our React friend list code:

// Dependencies
import React, { useState } from 'react'

// Types
import { FriendsType } from './../types/types'

// MUI
import { Box, Button } from '@material-ui/core'

// Styles
import useStyles from './MyList.styles'

// Interface
interface Props {
  data: FriendsType[]
}

const MyList = ({ data }: Props) => {
  // Local state
  const [showList, setShowList] = useState(false) // The value of showList is false

  // Style
  const classes = useStyles()

  return (
    <Box className={classes.mainContainer}>
      <Button
        variant="contained"
        color="primary"
        {/* Everytime that I click the button I'm changing the showList value to true or false */}
        onClick={() => {
          setShowList(!showList)
        }}
      >
        {/* If showList is true then show 'Hide List' text */}
        {/* If showList is false then show 'Show List' text */}
        {showList ? 'Hide List' : 'Show List'} {/* This is called ternary condition */}
      </Button>

      <Box>
        {/* This local state called 'showList' have a true value? */}
        {/* YES! showList have a true value - > Then rendering! */}
        {/* NO!  showList doesn't have a true value -> Don't rendering. */}
        {showList && (
          <ul className={classes.list}>
            {data.map((friend, index) => {
              return <li key={`friend-${index}`}>{friend.name}</li>
            })} {/* This is called short circuit condition */}
          </ul>
        )}
      </Box>
    </Box>
  )
}

export default MyList

Nice! in the next post I’m going to show you how to add multiple conditions in the same short circuit condition.

By Cristina Rojas.