Jonathan Pein
Jonathan Pein

Reputation: 59

I am struggling to iterate through an array in React

I am simply trying to print a list of what is an my array into another div. It does not seem to be working. The code is below

import React from "react";
import "./navbar.css";

class Navbar extends React.Component{
  render(){
    const categories = ["Art", "Films", "Brands", "Restaraunts"];
    var categoryList = categories.forEach(function(category){
              return <div className='navbar-item'>{category}</div>;
          })
    // Real thing would equal const category = this.props.category.name;
    return(
      <div className='navbar'>
          { categoryList }
      </div>
      );
  }
}

export default Navbar;

Any help would be greatly appreciated.

Thanks

Upvotes: 0

Views: 164

Answers (3)

Andrew
Andrew

Reputation: 121

Other answers are correct here, also worth adding that when returning a list like this React will nag you to add a key (this is due to how React handles indexes with element lists). A simple way to do this is to pass the key from the map.

Borrowing from the other examples you would end up with:

var categoryList = categories.map((category, key) => (
  <div key={key} className='navbar-item'>{category}</div>
);

It's worth noting that with this key, it will most likely not be very unique, especially in a complex application, and so tools eslint may insist you create one that is.

Upvotes: 1

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

Use map instead of forEach. map returns a new array, forEach doesn't.

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167220

Small issue. Replace forEach with map():

var categoryList = categories.map(function (category) {
  return (
    <div className='navbar-item'>{category}</div>
  );
});

Difference between forEach and map

Let’s first take a look at the definitions on MDN:

  • forEach() — executes a provided function once for each array element.
  • map() — creates a new array with the results of calling a provided function on every element in the calling array.

What exactly does this mean?

Well, the forEach() method doesn’t actually return anything (undefined). It simply calls a provided function on each element in your array. This callback is allowed to mutate the calling array.

Meanwhile, the map() method will also call a provided function on every element in the array. The difference is that map() utilizes return values and actually returns a new Array of the same size.

Improvements

Also, quick suggestion, if I may? Use arrow functions.

var categoryList = categories.map(category => (
  <div className='navbar-item'>{category}</div>
);

Upvotes: 4

Related Questions