This tutorial aims to get you started with Next.js, a popular React framework that offers features such as server-side rendering and static site generation. By the end of this tutorial, you will have set up your Next.js development environment and created your first Next.js application.
The user will learn how to:
Prerequisites:
- Basic knowledge of JavaScript and React
- Node.js and npm installed on your system
First, you need to install Next.js. We'll use create-next-app
, which sets up everything automatically for you. To create a new Next.js application, open your terminal and run:
npx create-next-app@latest nextjs-tutorial
This will create a new directory called nextjs-tutorial
with the initial project structure and dependencies.
Navigate into your new project directory:
cd nextjs-tutorial
You'll see several directories and files. The most important ones are:
pages/
: Any file inside the pages
directory will be treated as a route.public/
: The public directory is where you put any files that will be served directly by the server.styles/
: This directory is for your CSS files.Next.js uses a file-based routing system. That means if you create a React component file in the pages
directory, it will automatically be available as a route.
Let's create a new file about.js
in the pages
directory:
touch pages/about.js
Open about.js
and add the following code:
function About() {
return <div>About us</div>
}
export default About;
Here's the code for your first Next.js page:
// pages/about.js
function About() {
// A simple React component
return <div>About us</div>
}
// Exporting the component to be used as a page
export default About;
When you navigate to http://localhost:3000/about
in your browser, you'll see "About us" displayed.
Next.js has built-in support for navigation using the Link
component. Here's how you can link from your index page to the about page:
// pages/index.js
import Link from 'next/link'
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link> // Navigates to the about page when clicked
</div>
)
}
Now when you visit http://localhost:3000
, you'll see a link to the About page.
In this tutorial, you've learned how to install and set up Next.js, create a new Next.js project, and build a simple Next.js application with multiple pages and navigation. Your next steps could include learning more about Next.js features such as data fetching and API routes.
Additional resources:
- Next.js Documentation
- Learn Next.js
contact.js
) in the pages
directory and add a Link
to it in index.js
.about.js
page to include a title and a paragraph of text.<h1>
and <p>
element to the About
component.styles
directory and import it into your page components.styles.css
file, write some CSS rules, and import it with import '../styles/styles.css'
.