Next.js development basics
In this page, we will look at some basic topics:
- Creating the homepage
- Previewing the page on a local server
- Routing to subpages
- Linking among pages
Creating the homepage
To start our Next.js homepage, let's:
- go our project folder
- go to our app folder
- create a file called page.tsx
Then, let's copy this in:
export default function Main() {
return (
<h1>Home</h1>
)
}
Previewing the page on a local server
Before we have a look at the page on a local server, let's open the file package.json and add the test
and dev
properties to the scripts
object:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "next dev"
}
So, on our Terminal, when we run:
npm run dev
...a browser window will automatically open to localhost:3000 upon which we will see:
- a simple page with a large heading that says "Home"
- a hot reload every time we save a change onto app/page.tsx (or any similar file)
Routing to subpages
Website often have more than one page, so let's 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 adding folders and files!
In the app folder, we would create a route by creating a new folder. Let's call it about. Then, inside that folder, we would create a page by creating a new file. We will have to call this page.tsx. Thus, we create this folder and file structure:
- project
- app
- about
- page.tsx
- about
- app
Note, that we cannot call page.tsx by any other name due to the rules of Next.js!
Now, in project/app/about/page.tsx:
export default function About() {
return (
<div>
<h1>About</h1>
<p>This is my about page!</p>
</div>
)
}
Then, in Terminal:
npm run dev
Then, in the browser, we would go over to localhost:3000 and see the new page!
Linking among pages
We can then link between two pages by using the Link
library that comes with Next.js:
import Link from "next/link"
export default function About() {
return (
<div>
<h1>About</h1>
<p>This is my about page!</p>
<p><Link href="/">Go back to home page</Link></p>
</div>
)
}
Linking any page
To link the about page (or any page) from the home page, we can thus do the same:
import Link from "next/link"
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
So, there we have it, our single-page Next.js app now has (the illusion of having) multiple pages!