'How to create table of content from markdown content in NextJS?

I created a blog detail page in NextJS, where blog content is markdown.

import { serialize } from "next-mdx-remote/serialize";
import { MDXRemote } from "next-mdx-remote";

const PostDetails = ({ post, source }) => {
  const router = useRouter();

  if (router.isFallback) {
    return <Loader />;
  }

  return (
    <>
      <Head>
        <title>Basir - Blogs</title>
      </Head>
      <div className="container mx-auto px-4 lg:px-6 my-24">
        <div className="max-w-4xl px-4 lg:px-8 mx-auto">
          <PostDetail post={post} />

          <div className="prose">
            <MDXRemote {...source} />
          </div>

        </div>
      </div>
    </>
  );
};
export default PostDetails;

export async function getStaticProps({ params }) {
  
  const data = await getPostDetails(params.slug);
  const mdxSource = await serialize(data.content);

  return {
    props: {
      post: data,
      source: mdxSource
    },
  };
}


export async function getStaticPaths() {
  const posts = await getPosts();
  return {
    paths: posts.map(({ node: { slug } }) => ({ params: { slug } })),
    fallback: true,
  };
}

How do I create a table of content for the above blog detail page with clickable links that navigates the user to the respective blog heading?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source