loading...

Create ProductList and Product components

notrab profile image Jamie Barton ・1 min read

As we'll show a list of products in multiple pages across our store, let's create a component we can reuse.

Inside the src directory, create a new folder components. Inside here create the file Product.js, and add the following:

import React from "react";

export default function Product({ name, price }) {
  return (
    <p>
      {name}: {price.formatted_with_symbol}
    </p>
  );
}

This component is responsible for showing just the product name, and formatted with symbol price.

Now create the file ProductList.js, and add the following:

import React from "react";
import { Link } from "gatsby";

import Product from "./Product";

export default function ProductList({ products }) {
  if (!products) return null;

  return (
    <ul>
      {products.map((product) => (
        <li key={product.permalink}>
          <Link to={`/products/${product.permalink}`}>
            <Product {...product} />
          </Link>
        </li>
      ))}
    </ul>
  );
}

In this file we're mapping over the products prop, and rendering a list item that contains a Link, and the rendered Product component we created previously.

If there are no products, we don't render anything.

Discussion

pic
Editor guide