DEV Community

Martin Ratinaud
Martin Ratinaud

Posted on

Use Next.js <Link> component in posts with Markdown

For stakingcrypto.io I'm trying to store all content that is meant for blog, coin and exchange details in markdown components because I find it really easier to add and update data quickly.

A pain has always been to be able to insert <Image> and <Link> nextjs components as I always ending up with markdown files like this

Bad MDX formatting

As you can see, it does not look like markdown anymore and thus I can't ask not technical people to fill them up for me ☹️.

That's when I stumbled on this excellent post of Sebastien Castiel which fixed the <Image> problem in a very neat way. And I ended up with this:

Better MDX formatting with images

A lot better 😀, and I thus realized it would be very easy to replace those ugly links (<Link>) in the same way with one easy trick!

 <article className="prose lg:prose-xl"> {mdxContent && ( <MDXRemote components={{ ...components, a: ({ href, children }: any) => { if (href.startsWith('/')) { return ( <Link href={href}> <a>{children}</a> </Link> ); } return ( <a href={href} target="_blank" rel="noreferrer"> {children} </a> ); }, }} {...mdxContent} /> )} </article> 
Enter fullscreen mode Exit fullscreen mode

With this

  • for an internal link, [Stake Ethereum](/stake/ETH/ethereum)
  • for a _blank page, [Stake Ethereum](https://stakingcrypto.io/stake/ETH/ethereum)

So easy to write and a lot neater

Better MDX formatting with images and links

I now can also then add some nice CSS tweaks to add a small icon next to those external links.

Splendid! 🤩

Thanks for reading and follow me on Twitter for more

Top comments (0)