Home > database >  Map method in React and native js
Map method in React and native js

Time:11-05

I'm having trouble understanding how the map method works in React. In javascript, the map returns a new array and doesn't iterate, Why in React it is loop the elements

CodePudding user response:

In React if you provide an array of elements it renders them, so using a map we get a new array of elements and it's enough for JSX to render.

for example:

export function App() {
  return <div className='App'>{[<b>hello</b>, <h2>word</h2>]}</div>;
}

and it will render the elements as

<div className='App'>
  <b>hello</b>
  <h2>word</h2>
</div>

Learn more about it

CodePudding user response:

The map method does iterate over an array in Javascript. It just also happens to return a new array, who's elements are built using a callback function passed in to map which acts on each element of the original array.

For example:

let arr = [1, 2, 3, 4]

console.log(arr.map(num => num   1)) 


===> [2, 3, 4, 5] 

It works exactly like forEach, but instead of simply iterating, it returns a new array.

You can also use map to just make a shallow copy of the array:

let arr = [1, 2, 3, 4] 
let arrCopy = arr.map(num => num)

console.log(arrCopy)


===> [1, 2, 3, 4] 

Hence why it's easy to build out an array of elements using map in React:

let names = ["Mark", "Kelly", "Mike"]

return (
  <ol>
    {names.map(name => {
      return (
        <li>{name}</li>
      )})}
  </ol>
)
  • Related