Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through simple array of objects in React

I am not using JSX. Is this a problem? Is this considered bad practice?

var links = [
  { endpoint: '/america' },
  { endpoint: '/canada' },
  { endpoint: '/norway' },
  { endpoint: '/bahamas' }
];

class Navigation extends React.Component {
  render() {
    return (
      <div className="navigation">
        <ul>
          const listItems = links.map((link) =>
            <li key={link.endpoint}>{link.endpoint}</li> 
          );
        </ul>
      </div>
    );
}

Based on the basic list component section of the react docs, it seems like I should be able to print the contents of an array, the way I'm doing it inside my <ul></ul>

https://facebook.github.io/react/docs/lists-and-keys.html#basic-list-component

Is the problem that I am using an array of objects? The docs are using a simple array. I'd appreciate a push into the right direction.

like image 262
bruh Avatar asked Aug 24 '17 09:08

bruh


Video Answer


2 Answers

The issue is that your syntax is invalid, you should have something like this :

var links = [
  { endpoint: '/america' },
  { endpoint: '/canada' },
  { endpoint: '/norway' },
  { endpoint: '/bahamas' }
];

class Navigation extends React.Component {
  render() {
    const listItems = links.map((link) =>
        <li key={link.endpoint}>{link.endpoint}</li> 
    );
    return (
      <div className="navigation">
        <ul>
          {listItems}
        </ul>
      </div>
    );
}
like image 93
Daniel Andrei Avatar answered Sep 30 '22 03:09

Daniel Andrei


You should be able to do something like this:

    class Navigation extends React.Component {
      render() {
        return (
          <div className="navigation">
            <ul>
              {
                links.map(link =>
                  <li key={link.endpoint}>{link.endpoint}</li> 
                )
              }
            </ul>
          </div>
        );
    }
like image 25
Nocebo Avatar answered Sep 30 '22 03:09

Nocebo