Home > Enterprise >  How to iterate data from array?
How to iterate data from array?

Time:08-12

I'm developing a Products page using React. I have setup data like this

const data = {
  items: [
    {
      id: 1,
      name: 'Alloha Zune',
      brand: 'Alloha',
      slug: 'asus-zune-4',
      price: '90$',
      image: '/images/alloha_zune.png',
      category: 'Alloha',
    },
    {
      id: 2,
      name: 'Bacleim Pro',
      brand: 'Bacleim',
      slug: 'bacleim-pro',
      price: '110$',
      image: '/images/bacleim_pro.jpg',
      category: 'Bacleim',
    },
    {
      id: 3,
      name: 'Xarin Makeshift',
      brand: 'Xarin',
      slug: 'xarin-makeshift',
      price: '120$',
      image: '/images/xarin_makeshift.png',
      category: 'Xarin',
    },
   ],
  };

export default data;

I want to iterate these items as cards using reusable components.

The card component is as follows:

export default function Card() {
  return (
    <div>
      <>
        <div>
          <img
            src={item.image}
            alt={item.name}
          />
          <div>
            <h2>{item.name}</h2>
            <p>{item.price}</p>
            <ul>
              <p>{item.brand}</p>
              <p>{item.category}</p>
            </ul>
            <button type="submit" className="primary-button">
              Buy
            </button>
          </div>
        </div>
      </>
    </div>
  );
}

And I want to create another component such CardList Component to iterate over the data.

What will be the most code-efficient way to do this in React?

CodePudding user response:

Create a reusable Product Component and you can pass data to it in the form of props, like this

return (
        <div>
            {data.items.map(product => {
                return <ProductComponent ...product />
            })}
        </div>
)

Note I'm spreading the product object so that all the key-value pairs are passed to the component in the form of props

CodePudding user response:

You can map over the data.items and pass required props to Card component.

CODESANDBOX DEMO

export default function App() {
    return (
        <>
            {data.items.map((product) => {
                const { id, ...rest } = product;
                return <Card {...rest} key={id} />;
            })}
        </>
    );
}
  • Related