Next.js nth page
routing to and from the second page (and beyond)
Websites often have more than one page, so let's have a look at routing:
Routing just means moving from one "view" to another, most often by:
clicking on a link to get to another page
changing the URL on the browser's address bar
With React, we would do this by writing out a whole bunch of JSX to determine which route (URL) goes where
With Next.js, we create "routes" simply by using folders and files
like in the old HTML-only days!
Next.js routing
In the
app
folder, we would create a route by creating new folder, let's call itabout
Then, inside about, we would crate a page by creating a
page.tsx
fileDoing the above will create the
/about
route with this folder structure:
Unfortunately, due to Next.js rules, we cannot give this file a name other than page.tsx
In the code editor, open
page.tsx
Paste this in and save the file:
See this in action
In Terminal,
npm run dev
Let's go to
localhost:3000/about
(replace the port number 3000 if needed)
We will see the new page!
Linking between pages
We can then link between pages by using the Link
component that comes with Next.js:
Import
Link
as in line 1Add the
Link
tag as in line 9
We can also use the Next.js <Link>
tag just like HTML <a>
tag (with the href
and target
attributes that we know!)
Linking to any page
To link the about
(or any) page from the home page, we can thus do the same:
So, there we have it, our Next.js app has become a "single-page" app with the illusion of multiple pages!
Last updated