Next.js has a file-system based router built on the concept of pages. When a file is added to the pages directory it's automatically available as a route. The files inside the pages directory can be used to define most common patterns.
in react we used the react-router-dom to create pages and navigate between them
in next.js it's different . a page is a react component exported from a file in the pages directory. Each page is associated with a route based on its file name.
in pages
every file is mapped to a path
if we want to add a new page contact-us
in react you need to
-
creat a component
-
then add it in the app page inside the Router
<Route path = '/contact-us' component = {contact-us}/>
but in next.js you only need to add a new file contact-us
to your pages folder
pages/contact-us => "localhost:3000/contact-us"
in react we used react-route-dom Link to navigate between pages
<Link to="/">Home</Link>
in next.js the link is used with a little difference
<Link href="/"><a>Home</a></Link>
href is the path inside pages
directory. This is the only required prop.
- create a folder and open it with vs Code
install package.json :
npm init -y
install next.js and react :
npm install next react react-dom
- Open package.json and add the following scripts:
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
- create a folder withthe name of
pages
- inside this folder create
index.js
file (this file represents our home page "/") - inside the
index.js file
add the following code :
function HomePage() {
return <h1>Welcome to Next.js!</h1>
}
export default HomePage
-
you can now run the project by using the command
npm run dev
-
check the
localhost:3000
-
now create a file with the name of
about.js
-
inside this file add a function that returns any string , and don't forget to export this function
-
now check your
localhost:3000/about
and make sure that the file name matches the path nameit's there 🔥 just as easy as that
- import Link
import Link from 'next/link'
- add a button element (and don't forget to add a parent element)
- add the Link element inside the button then add the path
<button>
<Link href = '/'>
<a>
go back
</a>
</Link>
</button>
-
now you can click the button in the About page and go back to the home page 😌
we will talk about Index routes and Nested routes later in this workshop and how Link them , but this should give you a general idea of how next.js Routing works.
ps: you can also install next js by useing the command :
npx create-next-app .
and it will download the necessary files