Rendering Lists in React
March 25, 2020
Rendering lists in React can be a little tricky, but it works just like vanilla JavaScript. When rendering a list directly in the template, you must use the map()
function as it returns a view. The forEach()
works similarly except it doesn’t return data so it won’t do you any good. However, you can use all types of loops outside of the template to build a list of components and render the list object to the view. Below are some examples.
class App extends React.Component {
numbers = [12,23,34,45,56];
render() {
return (
<div>
<ul>
{ this.numbers.map( (n,i) => <li key={i}>{n}</li>) }
</ul>
</div>
);
}
}
Alternatively, you can build the view first using the map()
function and just render the object in the template like the following.
xxxxxxxxxx
class App extends React.Component {
numbers = [12,23,34,45,56];
render() {
const li = this.numbers.map( (n,i) => <li key={i}>{n}</li>);
return (
<div>
<ul>
{ li }
</ul>
</div>
);
}
}
This time let’s use the forEach()
loop.
xxxxxxxxxx
class App extends React.Component {
numbers = [12,23,34,45,56];
render() {
const li = [];
this.numbers.forEach( (n,i) => {
li.push(<li key={i}>{n}</li>);
});
return (
<div>
<ul>
{ li }
</ul>
</div>
);
}
}
Finally, let’s just use the for loop, which also works similarly with the while loop.
xxxxxxxxxx
class App extends React.Component {
numbers = [12,23,34,45,56];
render() {
const li = [];
for(let i=0;i<this.numbers.length;i++){
li.push(<li key={i}>{this.numbers[i]}</li>);
}
return (
<div>
<ul>
{ li }
</ul>
</div>
);
}
}
Either way, so long as you can build the components you can then just use it in the template and let React render it.