So far, I simply created a Next.js app by running
npx create-next-app@latest nextjs-blog --use-npm --example "https://github.com/vercel/next-learn/tree/master/basics/learn-starter"
Following the docs, you quickly understand that, initially, most of the code you want to touch is in pages/index.js
or inside the pages
folder.
Pages Folder And Navigation
In Next.js, a page is a React Component exported from a file in the pages folder.
This is quite important to understand because each page is associated with a route. For example, let's assume we have two files like follows:
- pages/about.js that exports a React component called About
- pages/contacts.js that exports a React component called Contacts
By default, Next.js will create two routes /about
and /contacts
where the About and Contacts components will be accessible.
Adding Pages
Following what we said above, I created the following components:
// pages/about.js
export default function About() {
return <div>About</div>
}
// pages/contacts.js
export default function Contacts() {
return <div>Contacs</div>
}
And that's it! If you navigate to http://localhost:3000/about
you will see a white page with the About text in the top-left corner. This is almost magic!!
User Navigation
The next step is to create a simple navigation bar so users can visit other pages without changing the URL manually.
In Next.js, we need to use the <Link>
component instead of the plain <a>
tag. However, the most important attributes are the same.
So, if I want to have a basic navigation menu, I might try the following code in index.js
<div>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
<Link href="/contacts">Contacts</Link>
</div>
By adding a bit of style, we get to:
One of the main benefits of using the <Link>
component for client-side navigation is that the browser won't refresh the whole page, unlike using <a>
.
Finally, as reported in the docs, if you need to link to an external page outside the Next.js app, just use an <a>
tag.
Under The Hood
There are two things worth mentioning:
- Code Splitting: Next.js does code splitting automatically, which means it only loads the code that is requested. As a consequence, the landing page is loaded quickly even if your app has many other pages.
- Prefetching: In production (when your app is deployed and available to users) Next.js automatically prefetches the code for the linked page in the background. In the example above, both About and Contacts get loaded in the background when you open the Home page (e.g. index.js in this case).
Top comments (0)