0

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

1
  • there is no error when I run this. However, nothing returns leaving an empty div Commented May 4, 2020 at 12:30

3 Answers 3

4

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>
);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.