2

In Gatsby, I have file.md, and I'd like to generate multiple pages—one for each section of file.md.

gatsby-transformer-remark

When using gatsby-transformer-remark, I can get the HTML of an entire markdown file with allMarkdownRemark.nodes.html. How do I get the HTML of each section of the file? For instance:

file.md:

# section 1

**bold**

# section 2

foo

I'd like to get an array of section HTMLs, like:

[
  '<div><h1>section 1</h1><b>bold</b></div>', 
  '<div><h1>section 2</h1>foo</div>'
]

gatsby-plugin-mdx

With gatsby-plugin-mdx, when do I

query MyQuery {
  mdx {
    headings {
      value
      depth
    }
  }
}

I get

{
  "data": {
    "mdx": {
      "headings": [
        {
          "value": "Section1",
          "depth": 1
        },
        {
          "value": "Section2",
          "depth": 1
        },
      ]
    }
  },
  "extensions": {}
}

But when I do:

query MyQuery {
  mdx(headings: {elemMatch: {value: {eq: "Section1"}}}) {
    body
  }
}

The body is the entire file, not just Section1.

Loren
  • 13,903
  • 8
  • 48
  • 79

1 Answers1

2

In your markdown file, the file.md everything that is after the --- is the body of the markdown so directly, you can get parts of it.

I would suggest a different workaround using MDX (Markdown + JSX) which allows you to add React's logic inside a markdown file. Gatsby has a detailed plugin for that: https://www.gatsbyjs.com/plugins/gatsby-plugin-mdx/

Another workaround, without using the MDX would be using "sections" inside the markdown. For example, a structure like:

---
title: Test
section1:
  description: some description 
section2:
    title: Some **bold title** for the section 2
---
The rest of the body content

Will create a node for each section, so your object will look like allMarkdownRemark.nodes.section1.description and allMarkdownRemark.nodes.section2.title respectively.

Note that you can add all the markdown supported styling along with it.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • Thanks, the actual sections are very long, so don't fit well indented in frontmatter. I tried your gatsby-plugin-mdx suggestion but don't see how to get each section's content separately. Do you know how? I edited the question with my progress. – Loren Feb 24 '21 at 21:53
  • The body of an MDX is literally a JSX file, so add your components and wrap the content as you wish. – Ferran Buireu Feb 26 '21 at 05:54
  • I'm not sure how adding components can enable me to generate multiple pages from a single mdx file? – Loren Feb 28 '21 at 04:55
  • No, adding components in an MDX file will allow you to customize the sections of the markdown's body – Ferran Buireu Feb 28 '21 at 08:05
  • Okay, so it sounds like using `gatsby-plugin-mdx` is not a solution to my original question. – Loren Mar 01 '21 at 21:32