React Conditional Rendering — 1
Tags: tutorial, react, javascript
Published: 2021-01-06 22:28:52

###### *This article is sponsored by [Fiverr](http://www.fiverr.com/s2/fa85266916) - 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**
```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**
```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**

```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**
```jsx
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` 
```jsx
<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.

```jsx
{
    <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.

```jsx
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.

```jsx
const showPersons ? true : false; 
// where personList = true
```
- Since show person is true, we need a function to close it and open it again...

```jsx
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.

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

Below is the needed result:

```jsx
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 in any other programming language.

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

```jsx
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;
```

{% stackblitz react-3eqv1n %}

**Happy Coding!!!**

<a href="https://www.buymeacoffee.com/bellotech" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

{% user bello %}
#### 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](http://www.fiverr.com/s2/fa85266916) to find the perfect freelance services for your business or become a freelancer.

{% youtube EkPDLVqKkLc %}

[Support](https://dashboard.flutterwave.com/donate/3lo9klliqwbu) what I do and push me to keep making free content.