loading...

Create individual product pages

notrab profile image Jamie Barton ・1 min read

Just like we did for all categories, let's now create individual pages for our products.

This time inside src/templates, create the file ProductPage.js and add the following:

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

export default function ProductPage({ data: { product } }) {
  return (
    <React.Fragment>
      <h1>{product.name}</h1>
      <p>{product.price.formatted_with_symbol}</p>
    </React.Fragment>
  );
}

export const pageQuery = graphql`
  query ProductPageQuery($id: String!) {
    product: checProduct(id: { eq: $id }) {
      id
      name
      ...PriceInfo
    }
  }
`;

This template is simply rendering our product page, and formatted with symbol with price. You may want to include the image, and more!

Now inside gatsby-node.js we must also query all products, and use the createPage action for each of our products to generate the files at path /products/:permalink.

Update gatsby-node.js to look like:

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;

  const {
    data: { allChecProduct, allChecCategory },
  } = await graphql(`
    {
      allChecProduct {
        nodes {
          id
          permalink
        }
      }

      allChecCategory {
        nodes {
          id
          slug
        }
      }
    }
  `);

  allChecProduct.nodes.forEach(({ id, permalink }) =>
    createPage({
      path: `/products/${permalink}`,
      component: require.resolve(`./src/templates/ProductPage.js`),
      context: {
        id,
      },
    })
  );

  allChecCategory.nodes.forEach(({ id, slug }) =>
    createPage({
      path: `/categories/${slug}`,
      component: require.resolve(`./src/templates/CategoryPage.js`),
      context: {
        id,
      },
    })
  );
};

Discussion

pic
Editor guide