React Conditional Rendering —  2

React Conditional Rendering —  2

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article
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.

 
Share this

Impressum

TechStack Media was launched in the year 2020 to make the learning of web technologies easier and more fun.

My name is Bello Osagie, I am the founder of TechStack, and my focus is to give in-depth, senior-level knowledge of the course through a step-by-step approach. You will learn HTML, CSS, JavaScript etc.

You can find my posts on Dev.to, Medium, Hashnode, Hackernoon, and Blogspot

The approach is to first start with the basics, then advance to more topics. Lots of practical examples are added to make learning more easier. TechStack Media also includes videos apart from content writing to make sure you understand all the concepts in a particular topic or course. Contents are frequently updated, so you do not miss out on the latest technology.

If you need a contact me on any of my social media or email:

For exclusive web technology tutorials, join my patron page.

Proudly part of