DEV Community

loading...

Discussion on: How to Make a Markdown Blog With Next.js

Collapse
esnaremaussa profile image
Esnare Maussa

Hi Jose!

Thanks for the article, I was following along and everything working at my end.

However, I noticed that the links inside the markdown files reload the whole page. For instance, I have a Contact Us page which URL is /contact-us and there is a link to that page in one markdown file. If I click on that link, the whole page is reloaded. In other words, it's the same behaviour as if it was added an a tag rather than the Link tag from next.

Is there any way to swap the a tag for a Link tag from the links coming from the Markdown files?

Thanks in advance!

Collapse
joserfelix profile image
Jose Felix Author

Hi Esnare, thanks for reading my post! I'm glad you like it.

Yes, it is possible to switch the <a/> with <Link/>. However, there is a caveat: using <Link/> for links outside your Next.js page will error out. My recommendation would be to create a <Link/> for the contact page, and an <a/> for everything else.

So, to get started we have to modify React Markdown default <a/>. For that, we have the renderers prop:

<ReactMarkdown
     escapeHtml={false}
     source={content}
     renderers={{            
         link: LinkNode,
     }}
/>

After that, let's create the LinkNode component:

const LinkNode = (props) => {
  // Here is the magic
 // Change to any conditional to match your contact form.
  if (props.href === "/contact-us") {
    return (
      <Link href={props.href} passHref>
        <a>{props.children}</a>
      </Link>
    );
  }

  return <a href={props.href}>{props.children}</a>;
};

That's it! I hope this helped.

Collapse
esnaremaussa profile image
Esnare Maussa

Thanks for your reply Jose,

That's good stuff, I shall test it now :)

While researching on that issue, I noticed this library called MDX github.com/mdx-js/mdx. Basically, it lets you use react components directly on the markdown files. Here is the integration it with with Next.js: mdxjs.com/getting-started/next, I am going to test this one too :)

Thanks for all mate!

Thread Thread
joserfelix profile image
Jose Felix Author

Awesome!

I have read about MDX and it is really good for creating interactive blog posts. I didn't use it in this tutorial because it is not compatible with most git-based CMS. Some CMS like netlify-cms do support it with a plugin, but for me, it still isn't mature enough.

In the future, I will experiment with it more and see if there is an efficient solution.