ReactJS – Lists


ReactJS – Lists



”;


List and For

The most common pattern in React is to convert a collection of items into to React elements. JavaScript has lot of option to manipulate the collection. Let us see how to use collection using for loop in this chapter.

for loop

The simple and easy solution to use is the time tested for loop to loop over the collection and use JSX expression to create the final React elements. Let us create a React app and try to apply for loop.

Create a new application using create-react-app and start the application.


create-react-app myapp
cd myapp
npm start

Next, create a component, ExpenseListUsingForLoop under components folder (src/components/ExpenseListUsingForLoop.js)


import React from ''react''
class ExpenseListUsingForLoop extends React.Component {
   render() {
      return <table>
         <thead>
            <tr>
               <th>Item</th>
               <th>Amount</th>
            </tr>
         </thead>
         <tbody>
         
         </tbody>
         <tfoot>
            <tr>
               <th>Sum</th>
               <th></th>
            </tr>
         </tfoot>
      </table>
   }
}
export default ExpenseListUsingForLoop

Here, we created a basic table structure with header and footer.

Next, create a function to find the total expense amount. We will use it later in the render() method.


getTotalExpenses() {
   var items = this.props[''expenses''];
   var total = 0;
   for(let i = 0; i < items.length; i++) {
      total += parseInt(items[i]);
   }
   return total;
}

Here, getTotalExpenses loop over the expense props and summarize the total expenses. Then, add expense items and total amount in the render method.


render() {
   var items = this.props[''expenses''];
   var expenses = []
   for(let i = 0; i < items.length; i++) {
      expenses.push(<tr><td>item {i + 1}</td><td>{items[i]}</td></tr>)
   }
   var total = this.getTotalExpenses();
   return <table>
      <thead>
         <tr>
            <th>Item</th>
            <th>Amount</th>
         </tr>
      </thead>
      <tbody>
         {expenses}
      </tbody>
      <tfoot>
         <tr>
            <th>Sum</th>
            <th>{total}</th>
         </tr>
      </tfoot>
   </table>
}

Here,

  • Navigated each item in the expense array using for loop, generated table row (tr) using JSX and finally pushed it into expenses array.

  • We have used expenses array in the JSX expression to include the generated rows.

  • The getTotalExpenses method to find the total expense amount and add it into the render method.

The complete source code of the ExpenseListUsingForLoop component is as follows −


import React from ''react''
class ExpenseListUsingForLoop extends React.Component {
   getTotalExpenses() {
      var items = this.props[''expenses''];
      var total = 0;
      
      for(let i = 0; i < items.length; i++) {
         total += parseInt(items[i]);
      }
      return total;
   }
   render() {
      var items = this.props[''expenses''];
      var expenses = []
      for(let i = 0; i < items.length; i++) {
         expenses.push(<tr><td>item {i + 1}</td><td>{items[i]}</td></tr>)
      }
      var total = this.getTotalExpenses();
      
      return <table>
         <thead>
            <tr>
               <th>Item</th>
               <th>Amount</th>
            </tr>
         </thead>
         <tbody>
            {expenses}
         </tbody>
         <tfoot>
            <tr>
               <th>Sum</th>
               <th>{total}</th>
            </tr>
         </tfoot>
      </table>
   }
}
export default ExpenseListUsingForLoop

Next, update the App component (App.js) with ExpenseListUsingForLoop component.


import ExpenseListUsingForLoop from ''./components/ExpenseListUsingForLoop'';
import ''./App.css'';
function App() {
   var expenses = [100, 200, 300]
   return (
      <div>
         <ExpenseListUsingForLoop expenses={expenses} />
      </div>
   );
}
export default App;

Next, add include a basic styles in App.css


/* Center tables for demo */
table {
   margin: 0 auto;
}
div {
   padding: 5px;
}
/* Default Table Style */
table {
   color: #333;
   background: white;
   border: 1px solid grey;
   font-size: 12pt;
   border-collapse: collapse;
}
table thead th,
table tfoot th {
   color: #777;
   background: rgba(0,0,0,.1);
   text-align: left;
}
table caption {
   padding:.5em;
}
table th,
table td {
   padding: .5em;
   border: 1px solid lightgrey;
}

Finally, check the application in the browser. It will show the expenses as shown below −


List and For

ECMASCript 6 for loop

Let us change the application and use the for .. of loop introduced in ECMAScript 6.


for(const [idx, item] of items.entries()) {
   expenses.push(<tr><td>item {idx + 1}</td><td>{item}</td></tr>)
}

Here,

  • idx refers the index of the array.

  • item refers expense item in each position of the array.

  • entries method parses the array and return it as an array of key-value pair. key refers the index of the array and value refers the value of the array in the corresponding key.

If we don”t need index, then we can skip entries() method as shown below −


for(const item of items) {
   expenses.push(<tr><td></td><td>{item}</td></tr>)
}

Advertisements

”;

Leave a Reply

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