DEV Community

loading...

Create CategoryList and Category components

notrab profile image Jamie Barton ・1 min read

Similar to our ProductList and Product components, let's now do the same for categories.

In a new file Category.js within the src/components directory, add the following:

export default function Category({ name }) {
  return name;
}

This one is very basic! All we're doing in this example is rendering the name of our category.

Let's now create a component to list our categories, and render this component for each.

In a new file CategoryList.js inside src/components, add the following:

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

import Category from "./Category";

export default function CategoryList({ categories }) {
  if (!categories) return null;

  return (
    <ul>
      {categories.map((category) => (
        <li key={category.slug}>
          <Link to={`/categories/${category.slug}`}>
            <Category {...category} />
          </Link>
        </li>
      ))}
    </ul>
  );
}

Just like we were linking to products before, here we're now linking to categories.

You'll notice to for our categories uses a slug instead of permalink.

Discussion (0)

pic
Editor guide