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 uses a special HTML construct: *ngFor
The array to render — TS file
Angular uses *ngfor to render an array — HTML file
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 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.
The essence of mapping operation
In other words, the map()
transforms each item of the original array into elements of a new array.
The array to render — JS file
Use of map to render an array in React
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:
Validity in years: {{plan.validityInYears}}
Thereafter, map()
repeats steps 1. and 2. for each element of the original array.
map() in action
Edit: We need keys too while rendering an Array in React. See my piece on React keys here.
https://stackblitz.com/edit/angular-ngfor-sample-example?embed=1&file=src/app/app.component.ts
https://stackblitz.com/edit/react-map-example?embed=1&file=index.js
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