Skip to main content

Building pages and components

Getting Started with Building Pages and Components in Next.js

Next.js is a powerful JavaScript framework built on React.js that allows developers to build server-side rendering and static web applications. One of the core features of Next.js is its file-system based routing, which means that the structure of pages in a Next.js app is based directly on the file system. In this tutorial, we will learn how to build pages and components in Next.js.

Building Pages in Next.js

In a Next.js project, pages are React Components exported from a .js, .jsx, .ts, or .tsx file in the pages directory. Each file in the pages directory becomes a route that gets automatically processed and rendered by Next.js.

Let's create a simple page. Create a new file in the pages directory and name it about.js. Inside about.js, write the following code:

function About() {
return <div>About us</div>
}

export default About

Now, if you navigate to http://localhost:3000/about, you will see the text "About us".

Building Components in Next.js

Components in Next.js are reusable pieces of code that return a React element to be rendered on the page. You can define components in the same file or in separate files.

Let's create a simple component. Create a new file in your project and name it Header.js. Inside Header.js, write the following code:

function Header() {
return <h1>Welcome to our website!</h1>
}

export default Header

Now you can use this component in any of your pages. Let's add it to the about.js page. Import the Header component at the top of the about.js file:

import Header from '../components/Header'

Then, you can use it inside the About component:

function About() {
return (
<div>
<Header />
<div>About us</div>
</div>
)
}

export default About

Now, if you navigate to http://localhost:3000/about, you will see the text "Welcome to our website!" followed by "About us".

Linking Between Pages

Next.js comes with a built-in <Link> component for navigating between pages. The <Link> component allows user to navigate between different pages in your application.

Let's create a new page named contact.js and add a link to it in the about.js page.

import Link from 'next/link'
import Header from '../components/Header'

function About() {
return (
<div>
<Header />
<div>About us</div>
<Link href="/contact"><a>Contact Us</a></Link>
</div>
)
}

export default About

Now, when you navigate to http://localhost:3000/about, you will see a "Contact Us" link. When clicked, it will take you to the contact page.

This is the basic understanding of how to build pages and components in Next.js. From here you can start building more complex applications by combining multiple components and pages. Happy coding!