Open In App

Next.js Pages

Last Updated : 05 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of the dynamic path helps in rendering your NextJS components conditionally.

In Next.js, a page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. We can easily create different pages in next.js and access them in browsers without using the router to redirect the user. In Next.js, you can also create dynamic pages. For this, you just have to add square brackets in the name of the file.

Create NextJS Application: You can create a new NextJS project using the below command:

npx create-next-app gfg

After creating your project folder (i.e. gfg), move to it by using the following command.

cd gfg

Project Structure: It will look like this.

 

Creating a new static page: Here we are going to create a new page with the name gfg. For this, we will create a new JavaScript file in our pages directory with the name ‘gfg.js‘. After creating the file add the below content in the file.

Javascript




import React from 'react'
  
export default function Gfg() {
  return (
    <h1>
      This is new file
    </h1>
  )
}


By default, the index.js file will be treated as the homepage of your app. Add the below content in the index.js file.

Javascript




import React from 'react'
  
export default function Homepage() {
  return (
    <h1>
      This is Homepage
    </h1>
  )
}


Now we can easily access both pages in our app by running the app in the browser.

Step to Run Application: Run the application using the following command from the root directory of the project.

npm run dev

Output:

Creating Dynamic pages: For this, we are going to create a new folder with the name route and inside this folder, we are going to create our dynamic file with the name [gfg].js.

Add the below content in the [gfg].js file:

Javascript




import React from 'react'
import {useRouter} from 'next/router';
  
export default function getRoute() {
    // Calling useRouter() hook
    const router = useRouter()
    return (
        <div>
            <h1>GeeksforGeeks</h1>
            <h2>pathname:- {router.asPath}</h2>
        </div>
    )
}


Here we are reading the value of the current route with the help of a router.

Step to Run Application: Run the application using the following command from the root directory of the project.

npm run dev

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads