DEV Community

Cover image for Building with Next.js - part 3
Lorenzo Zarantonello for This is Learning

Posted on • Updated on

Building with Next.js - part 3

So far, I simply created a Next.js app by running

npx create-next-app@latest nextjs-blog --use-npm --example ""
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
// pages/contacts.js
export default function Contacts() {
  return <div>Contacs</div>
Enter fullscreen mode Exit fullscreen mode

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!!

Next.js About page

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

  <Link href="/">Home</Link>
  <Link href="/about">About</Link>
  <Link href="/contacts">Contacts</Link>
Enter fullscreen mode Exit fullscreen mode

By adding a bit of style, we get to:

Next.js Home page

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)