-1

I'm trying to print JSON data (this) in React. I came to this:

const print = data.forEach(e => {
    e.data.map(el => {
      return(
        <li>{el.account_id}</li>
      )
    })
  });
  return (
    <div>
      <ul>
        {print}
      </ul>
    </div>
  );

Yet it doesn't work (when i do console.log(el.account_id) it logs everything, but doesn't display the data in the ul). What am i doing wrong?

EDIT:

const print = data.map(e => {
        return e.data.map(el => {
          return(
            <li>{el.account_id}</li>
          )
        })
      });
return (
   <div>
      <ul>
        {print}
      </ul>
   </div>
);

is the correct way to do it.

schmatteo
  • 13
  • 5
  • @Andy - print is a variable, that should be OK. The core issue is forEach doesn't return the elements being constructed. – Dave Feb 18 '22 at 23:09
  • i changed the code to `const print = data.map(e => {return e.data.map(el =>{return...` and now it works, thanks for help :) – schmatteo Feb 18 '22 at 23:18
  • you can accept the answer. https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Dave Feb 18 '22 at 23:38

2 Answers2

-1

You're very close. forEach does not return anything. Use map.

You probably want something closer to this:

const print = data.map(record => (
  <div key={record.meta.page}>
    <h3>PAGE: {record.meta.page}</h3>
    <ul>
      {record.data.map(item => {
        return (<li key={item.account_id}>{item.account_id}</li>)
      })
      }
    </ul>
  </div>
))

return (
  <div>
    {print}
  </div>
)
Dave
  • 7,552
  • 4
  • 22
  • 26
-1
const print = data.map(el => {
  return(
    <li>{el.account_id}</li>
  )
})
return (
  <div>
    <ul>
      {print}
    </ul>
  </div>
);

you dont need the forEach

Prince Abalogu
  • 385
  • 2
  • 4
  • 17