React Dynamic List using map() & If;Else and Switch Conditional Expression in JSX Template Rendering

In this React tutorial, we’ll look into some basic expression rendering methods in the components JSX template including dynamic looping over the Object to create a list, using conditional expressions lie if; else and Switch case to manage multiple conditions.

What is JSX in React?

First, let’s have a look at JSX which is used to add template in the component to create DOM elements. JSX stands for JavaScript XML. It allows us to write HTML to React making it easier to write and add HTML.

JSX looks like HTML but it is rendered as Javascript. So we can use Javascript methods inside the JSX template by wrapping them with {} braces.

 

How JSX is rendered in a function or class Component?

In a React component of type function or a class, we use render() method to define the JSX template which in turn converts it into an HTML. A React component can be of function or class type.

The type depends on the purpose and how much control is required in a component.

Function Component

Let’s have a look at the default App functional component

// ~src/App.js
import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">
      <div>Hello World, This is Jolly</div>
    </div>
  );
}

export default App;

Class Component

A function component by default returns the rendered HTML by calling the render() method. But if we convert the above App function component into a class, it will look like this:

// ~src/App.js
import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App" >
        <div>Hello World, This is Jolly</div>
      </div>
    )
  }
}

export default App;

Both above will create similar results in the browser.

 

How to Traverse or Loop over Object data?

In an Angular application, we usually use predefines directive like ng-repeat in version 1 and *ngFor structural directive in Angular 2+ version to render a list of items by assigning a collection object.

But in React, there is no such property available which can be used to traverse over the Collection of data or Objects. So we use the Javascript map() method to loop over the items.

Define an Object dataCollection inside the App component. The template will have the map() method to loop over the items inside the collection as shown below:

// ~src/App.js
import React from 'react';
import './App.css';

function App() {

  const dataCollection = [
    {
      id: 1,
      title: 'repellendus id ullam'
    }, {
      id: 2,
      title: 'excepturi consequatur est'
    }, {
      id: 3,
      title: 'eius doloribus blanditiis'
    }
  ];

  return (
    <div className="App">
      <div>My Item List</div>
      <ul>
        {
          dataCollection.map((item) =>
            <li key={item.id}>{item.title}</li>
          )
        }
      </ul>
    </div>
  );
}

export default App;

This will render the list of items on the browser:

 

Why we use key property on lists?

On looking closely you will notice the key property with id value. It is used to uniquely provide an identifier to each item traversed dynamically so that React can keep a close watch and track it on Virtual DOM.

If we don’t provide key React will throw a warning:

Warning: Each child in a list should have a unique “key” prop.


Basically, it is an optimization method to React. Whenever any item in the list is updated, then instead of re-render the complete list, React will update only a single item whose content is updated. This is possible for React in the availability of a key.

What if we don’t have any id or unique key in the collection?

It’s simple to apply the key even then. The map() method with each item also returns the index. We can use that index( starting from 0) as a key.

return (
    <div className="App">
      <div>My Item List</div>
      <ul>
        {
          dataCollection.map((item, index) =>
            <li key={index}>{item.title}</li>
          )
        }
      </ul>
    </div>
  );

 

How to use If: Else in React JSX Template?

Sometimes we need to render the template or its sections conditionally. For example, show a message ‘No Records Available’ when the collection object is empty to build the list.

In actual we can’t simply use if; Else in the JSX template due to the render() method which breaks the template to use the createElement method under the hood.

But we can use it outside the Template. Check below example:

// ~src/App.js
import React from 'react';
import './App.css';

function App() {

  const dataCollection = [];

  let ListTemplate;
  if (dataCollection.length) {
    ListTemplate = dataCollection.map((item, index) =>
        <li key={index}>{item.title}</li>
      );
  } else {
    ListTemplate = <li> No Message Found </li>;
  }

  return (
    <div className="App">
      <div>My Item List</div>
      <ul>
        {ListTemplate}
      </ul>
    </div>
  );
}

export default App;

 

Using Ternary Expressions (?:) inside the JSX

As we can’t use If; else in the JSX template directly, So, instead of If; else we can also use the ternary expressions as shown below:

function App() {

  const dataCollection = [{
    id: 1,
    title: 'repellendus id ullam',
    label: 'Dolorem officiis temporibus.'
  }];

  return (
    <div className="App">
      <div>My Item List</div>
      <ul>
        {
          dataCollection.length ? (
            dataCollection.map((item, index) => <li key={index}>{item.title}</li>)
          )
            : <li> No Message Found </li>
        }
      </ul>
    </div>
  );
}

 

How to use the Switch Case in the JSX for multiple conditions?

The ternary expression is used to handle only a single case to check if the expression returns true or false. But in case we have multiple cases to evaluate the JSX template, then we can use Switch case statements.

// ~src/App.js
import React from 'react';
import './App.css';

function App() {

  const msgType = "resolved";

  return (
    <div className="App">
      <div>Status of your ticket</div>

      {(() => {
        switch (msgType) {
          case "resolved": return (
            <div className="msg-resolved">
              Your Ticker is Resolved Successfully
            </div>
          )
          case "pending": return (
            <div className="msg-resolved">
              Your Ticker is pending
            </div>
          )
          case "closed": return (
            <div className="msg-closed">
              Your Ticker is Closed Successfully
            </div>
          )
          default: return (
            <div className="msg-empty">
              The Ticket Status is unknown. Check back later.
            </div>
          )
        }
      })()}

    </div>
  );
}

export default App;

In a Switch case, we add an expression in each case matching to the value passed in the switch() method. The matched case is then returned inside the JSX to render on DOM.

The default case is selected if none is matched.

 

Conclusion

JSX acts like Javascript so it can be easily empowered by adding methods supporting expressions. In the above tutorial, we discussed examples to build a dynamic list using map(), if; else expression in the component to return JSX in a variable, ternary expressions inside the JSX template. If we have multiple expressions to evaluate then we use Switch; case; break inside the JSX.

Hope this helped as a quick handy tutorial. Do share with others and comment your feedback.

Stay Safe!

 

Leave a Comment

Your email address will not be published. Required fields are marked *