Saturday, March 6, 2021

Displaying List in React

Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus in a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating lists. We can create lists in React in a similar manner as we do in regular JavaScript. We will see how to do this in detail further in this article.

Using JSX we can show lists using JavaScript's built-in Array.map() method. The .map() method is often used to take one piece of data and convert it to another. In our scenarios, we are taking data and converting it to a piece of our view.

A Simple Example

Let's say we have a list of array that we want to show in a list:

 

import React from "react";

export default function ArrayMap() {

  const arr = [1020304050];

  const newArr = arr.map(function (num) {

    console.log("Num"num);

    return <li>{num * 2}</li>;

  });

  console.log("Old Array"arr);

  console.log("New Array"newArr);

  return <ul>{newArr}</ul>;
}

  

This component uses Array’s built-in map function to create a new array newArr that has the same number of elements, and where each element is the result of calling the function you provide. The {} brackets are used to render the array of elements.

import React from "react";

export default function ArrayMap() {

  const arr = [1020304050];

  return (

    <ul>
      { 
arr.map((num=> {

        return <li>{num}</li>;
      })}

    </ul>

  );
} 

 

The above is the shorthand code for write the map function. Since we are not doing anything in the function's block body, we can also refactor it to a concise body and omit the return statement and the curly braces for the function body:

return (
  <ul>

    {arr.map(num =><li>{num}</li>)}

  </ul>
);


Rendering lists inside Components

So from the component’s point of view, we have to pass a list to a component using props and then use this component to render the list to the DOM. We can update the above code in which we have directly rendered the list to now a component that will accept an array as props and returns an unordered list. 

 

const mylist = [1020304050];

const App = () => <ListComponent list={mylist} />;

const ListComponent = ({ list }) => (

  <ul>

    {list.map((item=> (

      <li>{item}</li>

    ))}

  </ul>
);
export default App;

You can see in the above output that the unordered list is successfully rendered to the browser but a warning message is logged to the console.  

Warning: Each child in an array or iterator

         should have a unique "key" prop 

The above warning message says that each of the list items in our unordered list should have a unique key. A “key” is a special string attribute you need to include when creating lists of elements in React. We will discuss about keys in detail in further articles. For now, let’s just assign a key to each of our list items in the above code.

Below is the example where we display the list of Objects with keys.  

 

Display Object List in React

Displaying items from a list of objects in React is very simple. We can iterate over a list of objects using the .map() method in React JSX. Here is the example in which we mapped a list of objects and displayed them in the React app.

 

import React, { useState } from "react";


import "../node_modules/bootstrap/dist/css/bootstrap.css";

export default function DemoMap() {

  const [useraddUser] = useState([
    {
      id: 1,
      username: "pankkap",
      password: "pankaj123",
    },
    {
      id: 2,
      username: "manishkumar",
      password: "manish456",
    },
    {
      id: 3,
      username: "sachinyadav",
      password: "sachin789",
    },
  ]);

  const renderUser = (userindex=> {
    return (

      <tr key={index}>

        <td>{user.id}</td>

        <td>{user.username}</td>

        <td>{user.password}</td>

      </tr>
    );
  };
  return (

    <div className="container mt-3">

      <table class="table">

        <thead class="thead-light">

          <tr>

            <th>#</th>

            <th>User name</th>

            <th>Password</th>

          </tr>

        </thead>

        <tbody>{user.map(renderUser)}</tbody>

      </table>

    </div>
  );
}

Output:

The key attribute is necessary for React to identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Since React uses a virtual DOM and depends on the key to identifying items of a list, so in the above list example, we provided a unique id to every list item.