logo

GatsbyJS - How to Add Sidebars

Last Updated: 2023-12-06

Some of the pages may share the same sidebar, however not sidebars are the same. To select sidebars page-by-page, use the frontmatter.

In markdown, add a sidebar field to the frontmatter:

---
title: GatsbyJS - Sidebar
sidebar: web
---

Then in page template, first query the sidebar field:

export const query = graphql`
  query($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      ...
      frontmatter {
        title
        sidebar
        ...
      }
      ...
    }
  }
`;

Create your sidebars as separate js files in components/sidebars folder, and make this helper to load them:

const getSidebar = (sidebar) => {
  try {
    const Sidebar = require("../components/sidebars/" + sidebar + ".js")
      .default;
    return <Sidebar />;
  } catch (e) {
    return null;
  }
};

Add the sidebar to the template:

export default ({ data }) => {
  const sidebar = data.markdownRemark.frontmatter.sidebar;
  return (
    <Layout>
      <div>
        <aside id="sidebar">{getSidebar(sidebar)}</aside>
        <div id="main">...</div>
      </div>
    </Layout>
  );
};