DEV Community

loading...
Cover image for React Conditional Rendering —  2

React Conditional Rendering —  2

bello profile image Bello Updated on ・4 min read
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;
Enter fullscreen mode Exit fullscreen mode

If-else Statement

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Switch statement

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;
Enter fullscreen mode Exit fullscreen mode

Happy Coding!!!

Buy Me A Coffee

bello image

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.

Discussion (0)

pic
Editor guide