在本文中,我们将了解如何在 Next.js 中将一个页面链接到另一个页面。请按照以下步骤在 Next.js 应用程序中设置页面之间的链接:

要创建新的 NextJs 应用程序,请在终端中运行以下命令:

npx create-next-app GFG

创建项目文件夹(即 GFG )后,使用以下命令移至该文件夹:

cd GFG

项目结构:它看起来像这样。

创建页面:首先,我们将在 Next.js 项目中创建两个不同的页面。为此,在页面文件夹中创建两个名为“first”和“second”的新 JavaScript 文件。

 文件名:first.js

  • Javascript

export default function first() {

    return (

        <div>

            This is the first page.

        </div>

    )

};

Filename: second.js

  • Javascript

export default function second() {

    return (

        <div>

            This is the second page.

        </div>

    )

};

Linking the Pages: Now to link the pages, we are going to use the ‘Link’ component from ‘next/link’. We can add tag inside our Link component. We can add the below line in our script to import this component.

import Link from 'next/link'

To link the ‘first’ and ‘second’ page with the Homepage we are going to add the below lines in our index.js file in the pages folder.

Filename: index.js

  • Javascript

import Link from 'next/link'

export default function Home() {

    return (

        <div>

            {``}

            <h1>

                This is Homepage

            </h1>

            {``}

            <Link href=``"/first"``>

                <a><button>Go to First Page</button></a>

            </Link>

            <br />

            <Link href=``"/second"``>

                <a><button>Go to Second Page</button></a>

            </Link>

        </div>

    )

}

Filename: first.js Now we are also going to add the ‘Link’ component in our ‘first’ and ‘second’ pages.

  • Javascript

import Link from 'next/link'

export default function first() {

    return (

        <div>

            This is the first page.

            <br />

            {``}

            <Link href=``"/first"``>

                <a><button>Go to First Page</button></a>

            </Link>

            <br />

            <Link href=``"/second"``>

                <a><button>Go to Second Page</button></a>

            </Link>

        </div>

    )

}

Filename: second.js

  • Javascript

import Link from 'next/link'

export default function second() {

    return (

        <div>

            This is the second page.

            <br />

            {``}

            <Link href=``"/first"``>

                <a><button>Go to First Page</button></a>

            </Link>

            <br />

            <Link href=``"/second"``>

                <a><button>Go to Second Page</button></a>

            </Link>

        </div>

    )

}

运行应用程序的步骤: 现在使用以下命令运行应用程序:

npm start

 输出:

“这门课程充满了令人惊叹且组织良好的内容!本课程基于项目的方法可以更好地更快地理解概念。此外,现场课程的讲师非常优秀且知识渊博。”- Tejas |德意志银行

通过我们改进的全栈开发计划:掌握 Node.js 和 React,使您能够创建动态 Web 应用程序。

So get ready for salary hike only with our Full Stack Development Course.