ReactJS - Map



JavaScript Array datatype provides a range of easy to use function to manipulate the array and its values. The map() is one such function, which accepts a transform function and will create a new array by transforming each item in the given array by applying the transform function and return the newly created array.

The signature of the map function is as follows −

array.map(function(item, index, items), thisValue)

Here,

  • currentValue refers the value of the current element

  • index refers the index value of the current element

  • items refers the array of the current element

  • thisValue is the optional this value, which can be passed while invoking the map function

Let us consider that we have a list of numbers and wants to double each value in the array. We can do it in one line using map function as shown below −

var numbers = [2, 4, 6]
var transformed = numbers.map((val) => val + val)
for(var item of transformed) { console.log(item) }

Here, the output wil be as follows −

4
8
12

Example

Let us 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.

Next, add expense items and total amount in the render method.

render() {
   var items = this.props['expenses'];
   var expenses = []
   expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</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 we have,

  • Navigated each item in the expense array using map function, created table row (tr) for each entry using transform function and finally set the returned array in expenses variable.

  • Used expenses array in the JSX expression to include the generated rows.

  • Used 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 = []
      expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</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 −

ReactJS Map

Map in JSX

JSX allows any JavaScript expression to be included in it. Since map is just an expression in JavaScript, we can use it directly inside the JSX as shown below −

render() {
   var items = this.props['expenses'];
   var expenses = []
   
   // expenses = items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>)
   var total = this.getTotalExpenses();
   return <table>
      <thead>
         <tr>
            <th>Item</th>
            <th>Amount</th>
         </tr>
      </thead>
      <tbody>
         {items.map((item, idx) => <tr><td>item {idx + 1}</td><td>{item}</td></tr>)}
      </tbody>
      <tfoot>
         <tr>
            <th>Sum</th>
            <th>{total}</th>
         </tr>
      </tfoot>
   </table>
}
export default ExpenseListUsingForLoop
Advertisements