markdowngatsby

Make headings start at h2 in Gatsby markdown


I'm using Gatsby to build a basic blog website. I've run into an issue, which is that my existing blog posts use # headings within them, but my Gatsby blog has an h1 at the top of the page. I'd like for # in Markdown to become an h2, ## to be an h3, etc...

Is there an easy way to achieve this? gatsby-transformer-remark doesn't seem to have many options available, and even if it did I'm struggling to find an option on remark-parse or remark-stringify which would suit my purposes. I'd rather not write my own plugin if it can be avoided.


Solution

  • This is possible using the rehype-react module. In your blog-post template, add

    import rehypeReact from 'rehype-react'
    
    const renderAst = new rehypeReact({
      createElement: React.createElement,
      components: {
        h1: props => <h2>{props.children}</h2>,
        h2: props => <h3>{props.children}</h3>,
        // ...
      },
    }).Compiler
    

    and replace

    <div dangerouslySetInnerHTML={{ __html: post.html }} />
    

    with

    {
      renderAst(post.htmlAst)
    }
    

    and change html to htmlAst in your graphql query.

    Here is a more advanced example on using remark & gatsby.