Linking between pages in multi page Next.js React web applications

The Next.js React sample project only contains a single “Index” page. If your web site has multiple pages, you need to set up simple routing to call them from each other.

In this example we will use the “Link” Next.js React component to call two pages from each other with the minimum number of instructions using TypeScript.

Create the pages

File location

For automatic routing we need to place our pages into the “pages” directory. We can use nested folders, but in that case the call has to include the folder name too.

File locationURL
pages/index.tsx/ (index is the default file in every directory)
pages/addresses.tsx/addresses
pages/company/index.tsx/company (index is the default file in every directory)
pages/company/people.tsx/company/people

Requirements

  • Import the “Link” React component. It will automatically generate the URL to the referenced page,
  • “export” the function to make it available for routing,
  • Use the “<Link href=>” element to specify the target page hyperlink,
  • {/* */} is the comment block in React,
  • We use the .tsx file extension in our TypeScript applicaiton.

The code

This is the minimum code you need to call a page within your Next.js React web application.

The “pages/contact.tsx” file

// Import the Link component from next/link
import Link from 'next/link'

// Export the function to make it available to other modules
export default function Contact() {
  return (
    <>
    {/* Text on the page. */}
    This is the Contact page.<br/>
    {/* The link to the other page */}
    <Link href="/about">About</Link>
    </>
  )}

The “pages/about.tsx” file

// Import the Link component from next/link
import Link from 'next/link'

// Export the function to make it available to other modules
export default function About() {
  return (
    <>
    {/* Text on the page. */}
    This is the About page.<br/>
    {/* The link to the other page */}
    <Link href="/contact">Contact</Link>
    </>
  )}

Leave a comment

Your email address will not be published. Required fields are marked *