Sergey
Sergey

Reputation: 7682

ReactJS map through an array with objects

I have that part of code

const links = [
  {
    name: 'How it works',
    ref: '/'
  },
  {
    name: 'Calendar',
    ref: 'calendar'
  },
  {
    name: 'Contact me',
    ref: 'contact'
  }
];

const renderLinks = links.map((link, index) =>
  <li className="nav-item active" key={index}>
    <a className="nav-link" href={link.ref || "#"}>
      {link.name}
    </a>
  </li>
);

However when I try to render it an error is thrown.

render() {
    return (
      {renderLinks}
    );
  }

Objects are not valid as a React child (found: object with keys {renderLinks}). If you meant to render a collection of children, use an array instead.

As I think, I have to got an array but React thinks there is an object.

Upvotes: 1

Views: 2389

Answers (1)

dfsq
dfsq

Reputation: 193311

React thinks this is an object because you indeed provided an object. This is what it is if you write it without shortcut property notation:

render() {
  return {
    renderLinks: renderLinks
  );
}

Just return renderLinks directly without { }:

render() {    
  return renderLinks;
}

Upvotes: 2

Related Questions