Next.js markdown blog. Link component
Sergej Brazdeikis
Link component and why
I just noticed, that for internal links Next.js recommend to use <Link>
component.
Benefits?
- Code splitting automatically, so each page only loads what’s necessary for that page. That means when the homepage is rendered, the code for other pages is not served initially. And in a production build of Next.js, whenever Link components appear in the browser’s viewport, Next.js automatically prefetches the code for the linked page in the background. By the time you click the link, the code for the destination page will already be loaded in the background, and the page transition will be near-instant!
- Client-side navigation means that the page transition happens using JavaScript, which is faster than the default navigation done by the browser.
Implementation
Let's convert test markup:
['Next.js conf 2021'](https://nextjs.org/conf)
Adding draft code:
import Link from 'next/link' const components = { a: a => { return <Link href="/posts/first-post"> <a>this page!</a> </Link> } }
And shooting debug at it we can see the data available
And this is around nice result:
import Link from 'next/link' const components = { a: a => { return <Link href={a.href}> <a>{a.children}</a> </Link> } }
Extra
I noticed the following tip on Next.js website:
Note: If you need to link to an external page outside the Next.js app, just use an <a> tag without Link.
Let's implement that also!
I went with really simple implementation to check if link is local - works for me.
import Link from 'next/link' const components = { a: a => { const isLinkLocal = a.href.charAt(0) === "/" return isLinkLocal ? ( <Link href={a.href}> <a>{a.children}</a> </Link> ) : ( <a href={a.href}>{a.children}</a> ) }
Oh, and I think I may drop new window thingy for external links :D
<a href={a.href} target="_blank">{a.children}</a>
Links
Cheers!