Creating your first page
In this tutorial, we'll walk through the steps of creating your first page in Next.js. Next.js is a popular React framework for building server-side rendering and static web applications. One of its core features is a file-based routing system, which means that the pages of your app are defined by the files in the pages
directory.
Let's dive in!
Prerequisites
Before starting, you need to have Node.js and npm (which comes with Node.js) installed on your machine. If you haven't installed them yet, you can download them from here.
Setting Up The Next.js Project
First, let's create a new Next.js project. Open your terminal and run the following command:
npx create-next-app@latest my-app
Replace my-app
with the name of your project. This command will create a new Next.js application in a directory named my-app
.
After the installation process is finished, navigate to the project directory:
cd my-app
Then, start the development server:
npm run dev
You should now be able to see your application running at http://localhost:3000
.
Creating Your First Page
In Next.js, a page is a React Component exported from a .js
, .jsx
, .ts
, or .tsx
file in the pages
directory. Each page is associated with a route based on its file name.
Let's create a new page. In the pages
directory, create a new file called first-page.js
.
Open first-page.js
and add the following code:
function FirstPage() {
return <h1>This is my first page</h1>
}
export default FirstPage
In the code above, we define a new React component called FirstPage
and export it as default. This component will be associated with the /first-page
route.
To see your first page, open your browser and navigate to http://localhost:3000/first-page
. You should see "This is my first page" on the screen.
Linking Between Pages
Next.js provides a built-in <Link>
component for navigation between pages. The <Link>
component enables client-side transition between pages, which means the page transition happens in the browser, without making a request to the server.
Let's create a link to our first page. Open the index.js
file in the pages
directory and update the code as follows:
import Link from 'next/link'
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/first-page">
<a>Go to First Page</a>
</Link>
</div>
)
}
In the code above, we import the <Link>
component from next/link
and wrap our anchor tag <a>
with it. The href
prop on <Link>
should be the path to the page you want to navigate to.
Now, if you go back to http://localhost:3000
, you should see a link "Go to First Page". Clicking on this link will take you to your first page.
That's it! You've created your first page in Next.js and learned how to navigate between pages. Continue experimenting and exploring Next.js to build more complex applications. Happy coding!