SimpleNext.js
Navigation in Next.js with the Link component
Your Next.js app have multiple pages, but how would you navigate from one page to another? You can obviously use <a>
tag, but you will lose all the perks of client-side rendering as that would make a request to the server and would cause the browser to refresh for the new content. The best way to Navigate in a Next.js app is using the component, as we will see in detail in this article.
Simple use case of Next.js Link component
Just import the Link component from « next/link » and pass href property to the component.
Note that the Link component encapsulates an html tag, here for example an <a>
tag, but it could be any valid html tag.
import Link from "next/link";
const App = () => (
<div>
Hello World.{" "}
<Link href="/about">
<a>About</a>
</Link>
</div>
);
Add onClick to a Link
If you want to add a click event to your Link, add it to the HTML tag and not in the Link component :
import Link from "next/link";
const App = () => (
<div>
Hello World.{" "}
<Link href="/about">
<a onClick={() => console.log("clicked")}>About</a>
</Link>
</div>
);
Add query params to Next.JS link
Passing queries to a page is extremely helpful when the page template can handle dynamic data. Passing queries to the next route navigation is really simple.
import Link from "next/link";
const App = () => (
<div>
Hello World.{" "}
<Link
href={{
pathname: "/about",
query: { name: "Ruben" }
}}
>
<a>About</a>
</Link>
</div>
);
Instead of passing a string to the href property you may pass an object. That object will need the pathname value that points the route/page you want to send the user to. The next property to pass in the object is the query key. The query key is a key value object. The keys represent the param names, and the value will the param value.
Conclusion
We have seen how the Link component can be easy to use, but still can provide a better user experience by enabling client side navigation instead of server side navigation.