Angular vs. React: Rendering an Array

Scenarios Where You Need to Render an Array

No rocket science behind this — scenarios to render an array are commonplace. The array to render could be an array of heroes (see the mighty Heroes example). It could be an array of items to buy or chores to complete. Or a menu to render based on an array of options. Or maybe you are working for an insurance company and you have an array of plans to render. Perhaps you are creating an e-commerce website and you have items to render based on an array returned by a search operation. Arrays everywhere!

Angular’s Way: *ngFor

Angular uses a special HTML construct: *ngFor

Code

Angular vs. React
The array to render — TS file
Angular vs. React
Angular uses *ngfor to render an array — HTML file

Code explained

Line 6 sets up the *ngFor loop. It takes the first item of the plans array and renders lines 7 and 8 (in fact, any number of lines in between the tags where *ngFor is used — ul here) for it.

Step one is then repeated for each item in the array.

React’s Way: map()

React makes use of the JS map method for this purpose. What map() essentially does is to map (or transform) each element of the original array to the elements of a new array.
Angular vs. React
The essence of mapping operation

In other words, the map() transforms each item of the original array into elements of a new array.

Code

Angular vs. React
The array to render — JS file

Angular vs. React
Use of map to render an array in React

Code explained

Step 1. In effect, map() takes the first element of the plans array and puts it in the plan variable in line 48.

Step 2. It then creates a new array with the latter’s elements being:

  • {{plan.name}} — ${{plan.premiumInDollars}}
  • Validity in years: {{plan.validityInYears}}

    Thereafter, map() repeats steps 1. and 2. for each element of the original array.
    Angular vs. React
    map() in action

    Edit: We need keys too while rendering an Array in React. See my piece on React keys here.

    Full Examples

    Angular

    https://stackblitz.com/edit/angular-ngfor-sample-example?embed=1&file=src/app/app.component.ts

    React

    https://stackblitz.com/edit/react-map-example?embed=1&file=index.js

    Summary

    We often need to render an array in the UI.

    Angular does this by using *ngFor — an HTML construct.

    React does this by using map() — a JS method.

    That’s about it for rendering arrays in Angular and React.

    Happy coding!

    Originally published by Aanchal Kapoor at https://medium.com

    #Angular #React #javaScript #WebDev

    Angular vs. React: Rendering an Array
    23.25 GEEK