1. 15
    Use React Components for Native HTML Tags with MDX and Next.js
    2m 19s

Use React Components for Native HTML Tags with MDX and Next.js

Share this video with your friends

Send Tweet

The markdown rendering includes a lot of native HTML tags as well of course. Assume for instance we want to change the behavior of links within our rendered document. We can definitely create a custom component and include that in our MDX document, but we’d rather not want to have to use a specific <Link> component and rather be able to keep the native way of rendering links in Markdown, that is [some link](https://juri.dev).

Turns out that with next-mdx-remote we are able to automatically replace all rendered <a> tags (or really any other tag we want) with a React Component.

Prefer to read along as well? Here's the accompanying article.

~ 2 years ago

Link component on new NextJS doesn't accept anchor tags inside anymore, the fastest way to fix for me was adding the "legacyBehavior" prop

michaelbruns1
~ 2 years ago

I added 'slug' if there is any dynamic content and used inline conditionals. The 'children' prop was added to explicitly show that it is rendering the link's text Finally the '...otherprops' can be used for other properties we might want to use for the link.

export interface CustomLinkProps { href: string; slug: string | undefined; children?: React.ReactNode; }

export function CustomLink({href, slug, children, ...otherProps}: CustomLinkProps) { return ( <Link className='bg-yellow-100' href={${href}${slug? '/'+ encodeURIComponent(slug): ''}} {...otherProps}> {children || 'Example Text'} </Link> ); }