React Conditional Rendering —  1

React Conditional Rendering —  1

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.

The state was managed by adding an event listener to detect fired events in previous articles. This article will go even further to render components conditionally. The ternary operator, ? symbol in the ternary expression will be used to check if a condition is true or not, instead of the if-else statement.

Below are the existing code snippets to illustrate in this article:

index.css

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');

*,
*::before,
*::after {
    box-sizing: border-box;
}

html,
body {
    padding: 0;
    margin: 0;
}

body {
    background-color: #f0f0f0;
}

Person/Person.css

.Person {
    margin: 20px auto;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
    line-height: 1.7;
    width: 12.375rem;
    font-family: 'Roboto', sans-serif;
    background-color: white;
}

.Person-Card {
    display: inline-flex;
    margin: 5px;
}

.Person-Container {
    padding: 5px 20px;
    border: 1px solid #999;
}

body.module.css

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

button {
    border: 1px solid #000;
    border-radius: 4px;
    background-color: blueviolet;
    color: white;
    margin: 20px auto;
    padding: 10px;
    cursor: pointer
}

.btns {
    display: flex;
}

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 = () => {
    setState((prevState) => ({
      ...prevState,
      //  code here
    }))
  }

  return (
    <div className={bodyStyles.body}>
      <div className='Person-Container'>
        <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} />
        <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;

The 3 Person components, <Person /> are the list that can be toggled conditionally.

Below are the steps to toggle components in React (App.js).

Steps

For components to be toggled successfully, they need to be wrapped in a parent element.

  • Wrap the 3 <Person /> components in a div

    <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>
    
  • Place a curly bracket around it.

{
    <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>
}
  • Let's assume the expression in the curly bracket refers to a variable, personList. Assign the <Person /> components to the personList variable before the return keyword.
const personList = { <div>...</div> }
  • The ternary operator, the ? symbol checks if a condition is true or false. That is if personList is true, open the Person's components; else close if false.
const showPersons ? true : false; 
// where personList = true
  • Since show person is true, we need a function to close it and open it again...
const personsToggleHandler = () => {
    const showCards = state.showPersons;
    setState((prevState) => ({
      ...prevState,
      showPersons: !showCards
    }))
  }
  • Since hooks do not merge, the state needs to be spread on it. Do this in a function, personsToggleHandler. Also always reverse the condition when an event is fired open a click.
const personsToggleHandler = () => {
    const showCards = state.showPersons;
    setState((prevState) => ({
      ...prevState,
      showPersons: !showCards
    }))
  }

Below is the needed result:

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
    }))
  }

  return (
    <div className={bodyStyles.body}>
      <div className='Person-Container'>
        {
          state.showPersons ?
            <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> : false
        }
        <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;

A falsy statement can either be false, null, '', or undefined. Although false is used above, we will change it to null in the next example. This is generally true in vanilla JavaScript or any other programming language.

Since the Person's components is named, personList, the above code can be re-written as shown below:

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;

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