How to link multiple pages in Next Js using TypeScript
Linking multiple pages in Next Js is simple, I assume that you have built your Next Js project already and had it running. If not follow,
“How to set up Next Js in easy steps”.
I am going to explain these points in this blog:
- How to create an anchor tag using “next/link”.
- How to create an About page.
- How to link the Home and About pages.
How to create an anchor tag using “next/link”
First, go to your project directory, and in the path type “cmd” to open cmd, that’ll look like this:
As the cmd is open in your project directory, type:
code .
like this:
to open “vs code” in that directory.
As your project is opened, go to “page.tsx” file, and remove all the content written inside the return brackets.
Your page.tsx file should look like this:
You can see the empty tags, because functions always return a single value, same for this case,
either wrap your code inside a single div tag that gives a little gap by default or use these ‘<></>’ fragment tags that don’t give any space.
At the top of the page, write:
import Link from 'next/link;
Inside the Home function, do these steps:
1. Go inside the fragment tag.
2. Make a Link tag, add a href attribute give it the path like this: “/”.
3. Inside the Link tag, write, About.
After that, your Home function will look like this:
How to create an About page
Inside the app directory, create a new folder with the name “about”, and follow these steps:
- Copy the page.tsx file, and paste it inside the about folder. Or you can make a new ‘page.tsx’ file.
- Change the name of the function, from Home -> About.
- Remove the Link tag, add an h1 tag, and inside it write, “About Page”.
REMEMBER! To name the file page.tsx, else the page.tsx file inside the about folder won’t be accessible. It’ll be treated as a private directory.
Your About function will look like this:
How to link the Home and About pages
Coming back to the page.tsx file, where our Home function resides.
Just add, “about” inside the href attribute, and the link tag should look like this:
That’s it, time to see the results in the browser. Run the server, using
npm run dev
the command on the terminal. Go to the browser and type,
localhost:3000
Your link will be there, click on it and here we are:
in the About page.
Your project hierarchy should look like this:
‘src’ directory contains ‘app’ directory.
‘app’ directory contains, ‘about’ directory, ‘page.tsx’ file, and some other files.
‘about’ directory contains, ‘page.tsx’ file.
See how simple it was. What we did?
- Created a folder, and named it “about”.
- Made a “page.tsx” file in it, And a function with the name About.
- In the Home functions, inside the Link tag’s href attribute, we add the path: “/about”.
Voila!