1

I have an array of objects that looks like this:

const arr = [
{name: "Bill", email: "bill@email.com"},
{name: "Suzy", email: "suzy@email.com"},
{name: "Jill", email: "Jill@email.com"},
]

I would like to return each value in an <li>. One list for names, one list for emails. Like this:

return (
  <>
    <div className="names">
      <ul>
        {arr.forEach((item) => {
          return <li>item.name</li>;
        })}
      </ul>
    </div>

    <div className="emails">
      <ul>
        {arr.forEach((item) => {
          return <li>item.email</li>;
        })}
      </ul>
    </div>
  </>
);

so that it looks like this:

- Bill
- Suzy 
- Jill

- bill@email.com
- suzy@email.com
- jill@email.com

But, of course what I am doing does not look like this, which is why I am asking this question. What can I do with my array of objects to generate the desired list layout? Thanks.

Jon
  • 622
  • 8
  • 29

2 Answers2

1

You should use array.map in JSX, with your code:

{
  arr.map((item, index) => (
    <li key={index}>{item.email}</li> 
  ))
}
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
1

you can do it like this:

import React, { useState } from 'react';

const Component=()=> {

  const [data, setData] = useState({
    arr = [
      {name: "Bill", email: "bill@email.com"},
      {name: "Suzy", email: "suzy@email.com"},
      {name: "Jill", email: "Jill@email.com"},
    ]
  })

  return (
    <>
      <div className="names">
        <ul>
          //this map will render all the names inside arr array one by one inside an li
          {data.arr.map((item, index) => (
            <li key={index}>{item.name}</li> 
          ))
          }
        </ul>
      </div>

      <div className="emails">
        //this map will render all the emails inside arr array one by one inside an li
        {data.arr.map((item, index) => (
          <li key={index}>{item.email}</li> 
        ))  
        }
      </div>
    </>
  );
}