Skip to main content

Command Palette

Search for a command to run...

React Conditional Rendering —  2

Updated
•7 min read•View as Markdown
React Conditional Rendering —  2
B

Web technology related ➡️ blogger || video creator || author || online instructor || YouTuber || web developer || freelancer

This article is sponsored by Fiverr - Freelance to get extra income or become a full-time freelancer.

We saw how a list of components is toggled based on certain conditions. In this article, different approaches will be used. The if-else statement and switch statement. You can also use the if statement with the else-if statement just like in Vanilla JavaScript.

All Vanilla JavaScript can be used provided you are outside the JSX scope and the return keyword. That is, outside the root, parent component, and before the return keyword.

The example below is the code snippet in the previous article:

App.js

import React from 'react';
import { useState } from 'react';
import Person from './Person/Person';
import bodyStyles from './body.module.css';

const App = () => {
  const [state, setState] = useState({
    persons: [
      { name: 'Bello', language: 'React', id: '2sdr3' },
      { name: 'Michael', language: 'Vue', id: 'de6c3' },
      { name: 'Mary', language: 'Angular', id: 'c1z3x' }
    ],
    showPersons: true
  });

  const personsToggleHandler = () => {
    const showCards = state.showPersons;
    setState((prevState) => ({
      ...prevState,
      showPersons: !showCards
    }))
  }

  const personsList = (
    <div>
      <Person
        name={state.persons[0].name}
        language={state.persons[0].language}
        id={state.persons[0].id} />
      <Person
        name={state.persons[1].name}
        language={state.persons[1].language}
        id={state.persons[1].id} />
      <Person
        name={state.persons[2].name}
        language={state.persons[2].language}
        id={state.persons[2].id} />
    </div>
  );

  return (
    <div className={bodyStyles.body}>
      <div className='Person-Container'>
        {
          state.showPersons ? personsList : null
        }
        <h3
          style={{
            textAlign: 'center',
            fontFamily: 'sans-serif'
          }}>Toggle Persons</h3>
      </div>

      <div className={bodyStyles.btns}>
        <button
          className={bodyStyles.button}
          onClick={personsToggleHandler}>Toggle Person Cards</button>
      </div>
    </div>
  );
};

export default App;

If-else Statements

In React, code outside of the JSX scope is Vanilla JavaScript. This means we can use an alternative approach to check if a condition is true or false. Let's consider the if-else statement.

The code snippet below uses the if-else statement outside of the JSX scope.

import React from 'react';
import { useState } from 'react';
import Person from './Person/Person';
import bodyStyles from './body.module.css';

const App = () => {
  const [state, setState] = useState({
    persons: [
      { name: 'Bello', language: 'React', id: '2sdr3' },
      { name: 'Michael', language: 'Vue', id: 'de6c3' },
      { name: 'Mary', language: 'Angular', id: 'c1z3x' }
    ],
    showPersons: true
  });

  const personsToggleHandler = () => {
    const showCards = state.showPersons;
    setState((prevState) => ({
      ...prevState,
      showPersons: !showCards
    }))
  }

  let personsList = '';
  if (state.showPersons) {
    personsList = (
      <div>
        <Person
          name={state.persons[0].name}
          language={state.persons[0].language}
          id={state.persons[0].id} />
        <Person
          name={state.persons[1].name}
          language={state.persons[1].language}
          id={state.persons[1].id} />
        <Person
          name={state.persons[2].name}
          language={state.persons[2].language}
          id={state.persons[2].id} />
      </div>
    )
  } else {
    personsList = '';
  }

  return (
    <div className={bodyStyles.body}>
      <div className='Person-Container'>
        {personsList}
        <h3
          style={{
            textAlign: 'center',
            fontFamily: 'sans-serif'
          }}>Toggle Persons</h3>
      </div>

      <div className={bodyStyles.btns}>
        <button
          className={bodyStyles.button}
          onClick={personsToggleHandler}>Toggle Person Cards</button>
      </div>
    </div>
  );
};

export default App;

Ternary Expressions

An Expression can either be truthy or falsy after evaluation.

The condition is evaluated if the expression is truthy, else ignored if it is false. It is the best alternative to if-else statements.

condition ? expression1 : expression2;

The code snippet in the if-else statement can be in form of a ternary expression as shown below:

App.js

import React from 'react';
import { useState } from 'react';
import Person from './Person/Person';
import bodyStyles from './body.module.css';

const App = () => {
  const [state, setState] = useState({
    persons: [
      { name: 'Bello', language: 'React', id: '2sdr3' },
      { name: 'Michael', language: 'Vue', id: 'de6c3' },
      { name: 'Mary', language: 'Angular', id: 'c1z3x' }
    ],
    showPersons: true
  });

  const personsToggleHandler = () => {
    const showCards = state.showPersons;
    setState((prevState) => ({
      ...prevState,
      showPersons: !showCards
    }))
  }

  let personsList = false ?
    (
      <div>
        <Person
          name={state.persons[0].name}
          language={state.persons[0].language}
          id={state.persons[0].id} />
        <Person
          name={state.persons[1].name}
          language={state.persons[1].language}
          id={state.persons[1].id} />
        <Person
          name={state.persons[2].name}
          language={state.persons[2].language}
          id={state.persons[2].id} />
      </div>
    ) : state.showPersons;

  return (
    <div className={bodyStyles.body}>
      <div className='Person-Container'>
        {personsList}
        <h3
          style={{
            textAlign: 'center',
            fontFamily: 'sans-serif'
          }}>Toggle Persons</h3>
      </div>

      <div className={bodyStyles.btns}>
        <button
          className={bodyStyles.button}
          onClick={personsToggleHandler}>Toggle Person Cards</button>
      </div>
    </div>
  );
};

export default App;

Switch Statements

Switch statement is used to perform different actions based on different conditions.

The example above uses the switch statement to perform an action based on the condition:

import React from 'react';
import { useState } from 'react';
import Person from './Person/Person';
import bodyStyles from './body.module.css';

const App = () => {
  const [state, setState] = useState({
    persons: [
      { name: 'Bello', language: 'React', id: '2sdr3' },
      { name: 'Michael', language: 'Vue', id: 'de6c3' },
      { name: 'Mary', language: 'Angular', id: 'c1z3x' }
    ],
    showPersons: true
  });

  const personsToggleHandler = () => {
    const showCards = state.showPersons;
    setState((prevState) => ({
      ...prevState,
      showPersons: !showCards
    }))
  }

  let personsList;
  switch (state.showPersons) {
    case false:
      personsList = (
        <div>
          <Person
            name={state.persons[0].name}
            language={state.persons[0].language}
            id={state.persons[0].id} />
          <Person
            name={state.persons[1].name}
            language={state.persons[1].language}
            id={state.persons[1].id} />
          <Person
            name={state.persons[2].name}
            language={state.persons[2].language}
            id={state.persons[2].id} />
        </div>
      );
      break;
    default:
        personsList = true;

  }
  return (
    <div className={bodyStyles.body}>
      <div className='Person-Container'>
        {personsList}
        <h3
          style={{
            textAlign: 'center',
            fontFamily: 'sans-serif'
          }}>Toggle Persons</h3>
      </div>

      <div className={bodyStyles.btns}>
        <button
          className={bodyStyles.button}
          onClick={personsToggleHandler}>Toggle Person Cards</button>
      </div>
    </div>
  );
};

export default App;

Happy Coding!!!


Buy me a Coffee


Techstack | Fiverr

Techstack article, sponsored by Fiverr.

  • Connect to freelancers with proven business experience.
  • Get matched with the perfect talent by a customer service manager.
  • Freelance to get extra income or become a full-time freelancer.

Sign up to find the perfect freelance services for your business or become a freelancer.

Support what I do and push me to keep making free content.

React

Part 17 of 21

React is a popular front-end library for building fast UIs. Companies are in high demand for React developers because it is SEO-friendly. Google ranks a web app based on the rendering speed...

Up next

Looping through List components in React

This article is sponsored by Fiverr - Freelance to get extra income or become a full-time freelancer. In the previous article, we saw how to output content dynamically. There's one issue we need to tackle though. That is manually extracting the pers...