I'm learning react and reading this code: https://github.com/john-smilga/react-advanced-2020/blob/master/src/tutorial/4-forms/final/1-controlled-inputs.js (long...)
What I don't understand is this part (line 53-61):
{people.map((person, index) => {
const { id, firstName, email } = person;
return (
<div className='item' key={id}>
<h4>{firstName}</h4>
<p>{email}</p>
</div>
);
})}
Why is the return inside a map ? Since the map is taking items from the array and operating on them individually, won't there be multiple returns for each operation ?
Thank very much !
CodePudding user response:
const l = [1, 2, 3]
const mapped_array = l.map(li => {
console.log(li) // 1, 2, 3
return 10 * li
})
console.log(mapped_array)
/// [10, 20, 30]
CodePudding user response:
You don't need to destructure person properties, you can also use the other way-
{people.map((person, index) =>
(
<div className='item' key={person.id}>
<h4>{person.firstName}</h4>
<p>{person.email}</p>
</div>
))}
CodePudding user response:
You can read more about Array#map in the MDN docs.
map calls a provided callbackFn function once for each element in an array, in order, and constructs a new array from the results.
So the function that is called for each array element must return something. That return value is then used to construct the new array.
CodePudding user response:
This syntax:
() => { /* ... */ }
creates a function. The return
statement inside of it only returns that small function that was passed to the map()
function, but doesn't return from the outer function.