DEV Community

Kayut
Kayut

Posted on

3 1

How can I loop over this object in React?

Hi,

I'm learning React. In the following component, I import a JS file (data.js), which looks like a JSON file which includes an object.

Inside the return of the TinTinTile class, I use that object to display all data.
In my example bellow, I can only display the first array in the object. But I need a way to loop over the array jsonResponse.characters.

Now my question is:
How can I loop over jsonResponse.characters?

import React, { Component } from 'react';
import jsonResponse from './data';

console.log(jsonResponse);
// const ArrayLength = jsonResponse.characters.length;
// console.log(ArrayLength);

// jsonResponse.characters.foEach(function(i) {
//   console.log(i);
// });

class TinTinTile extends Component {
  state = {};
  render() {
    return (
      <ul id="container" className="cf">
        <li className="list-container">
          <img
            className="image-container"
            src={jsonResponse.characters[0].image_url}
            alt="kir"
          />
          <div className="text-container">
            <h4>Name: {jsonResponse.characters[0].name}</h4>
            <p>Job: {jsonResponse.characters[0].job}</p>
            <p>Age: {jsonResponse.characters[0].details.age}</p>

            <button className="btn">More details ...</button>
          </div>
        </li>
      </ul>
    );
  }
}

export default TinTinTile;

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (2)

Collapse
 
pdlozano profile image
David Lozano

Use the map() Function. Also, there’s no need to use Component. Use functional components instead if you don’t need state. Here’s the full code:

function TinTinTile() {
  const list = jsonResponse.characters.map((item, index) => {
    return (
      <li className="list-container" key={index}>
          <img
            className="image-container"
            src={item.image_url}
            alt="kir"
          />
          <div className="text-container">
            <h4>Name: {item.name}</h4>
            <p>Job: {item.job}</p>
            <p>Age: {item.details.age}</p>

            <button className="btn">More details ...</button>
          </div>
        </li>
    );
  });

  return (
    <ul id="container" className="cf">
      {list}
    </ul>
  );
}
Collapse
 
kayut profile image
Kayut

Great! Thanks a lot.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay