I have an array which contains objects. I am creating a map of this array to renders the names with a span
component.
let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];
I have been using the below two different functionalities to iterate on that array of objects, and using map to render JSX elements.
Functionality1:
import React, { Component } from 'react';
class App extends Component {
render() {
let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];
const items = data.map((key, i) => {
return <span key={key.id}>{key.name}</span>;
});
return (
<div>
{items}
</div>
);
}
}
export default App;
Functionality2:
import React, { Component } from 'react';
class App extends Component {
render() {
let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];
let rows = [];
data.map((key, i) => {
rows.push(<span key={key.id}>{key.name}</span>);
});
return (
<div>
{rows}
</div>
);
}
}
export default App;
I known to the above two different ways of using map
and rendering JSX elements. Is there any other ways of doing the same, apart from these two? If so, which is recommended?
The first way is better.
Array.prototype.map
creates an array behind the scenes and returns it after applying the modification on each element. Functionality-1 creates two arrays, while Functionality-2 creates three.Functionality-1 reads better. It's how React code usually being written. For a simple element like this, I'd save the const definition for items and put the map statement in the JSX to be returned directly.
Generally,
for
orwhile
statement is the most efficient way to iterate an array. The way a small array is processed in non-critical place can be considered microoptimisation.The use of
map
is idiomatic in React components because it's fast enough and can return a value as a part of an expression.While this is an antipattern:
map
is supposed to map array elements to other values (hence the name), not to iterate an array instead offorEach
or other loop. This problem can be tracked with ESLintarray-callback-return
rule.The component is stateless and doesn't need to be
Component
class. It can be functional component orPureComponent
class. Sincedata
is constant, it doesn't need to be assigned on each render: