Yoshi Walsh
Yoshi Walsh

Reputation: 2077

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.

Upvotes: 2

Views: 440

Answers (2)

azatris
azatris

Reputation: 21

I was looking for a solution for this as well and was able to solve this more simply. Note that I am using MDX.

File DowngradedHeaders.js:

import * as React from 'react';
    
export const H1 = props => <h2 {...props} />;
export const H2 = props => <h3 {...props} />;
export const H3 = props => <h4 {...props} />;
export const H4 = props => <h5 {...props} />;
export const H5 = props => <h6 {...props} />;

In the blog post file, wrap the {children} of the body as follows:

import { MDXProvider } from '@mdx-js/react';
import {H1, H2, H3, H4, H5} from "@/src/components/DowngradedHeaders";

const components = {
  h1: H1,
  h2: H2,
  h3: H3,
  h4: H4,
  h5: H5
};
<section itemProp="articleBody">
   <MDXProvider components={components}>
      {children}
   </MDXProvider>
</section>

Upvotes: 0

Jonathan
Jonathan

Reputation: 1088

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.

Upvotes: 1

Related Questions