Next.js Basics: Creating Pages and Basic Routing Explained

In the process of web application development, managing pages and navigating between them is a crucial aspect. In this article series, we will delve into the fundamentals of creating pages and implementing navigation in Next.js. These foundational concepts are essential for building flexible and manageable web applications.

Creating and Displaying the First Page

Firstly, let's understand how to create and display a simple page in Next.js. You can create pages by creating files within the pages directory of your project. For instance, to create a welcome page, you can create a file named welcome.js within the pages directory.

// pages/welcome.js
function WelcomePage() {
  return <h1>Welcome to Next.js!</h1>;
}

export default WelcomePage;

In the above code snippet, we've created a simple welcome page. When you access the /welcome path in your web browser, you'll see the message "Welcome to Next.js!" displayed.

Basic Routing

Next.js offers a robust and intuitive routing system that makes navigating between pages easy. Routing in Next.js is based on the pages directory, with each file in this directory corresponding to a specific path. For example, a file named about.js within the pages directory will create a page accessible at the /about path.

Creating Links and Navigation

To create links between pages and navigate between them, we can use the <Link> component from the next/link library. Below is an example of creating a link from the welcome page to the about us page.

// pages/welcome.js
import Link from 'next/link';

function WelcomePage() {
  return (
    <div>
      <h1>Welcome to Next.js!</h1>
      <Link href="/about">Learn more about us</Link>
    </div>
  );
}

export default WelcomePage;

In the example above, when you click the "Learn more about us" link, you'll be redirected to the /about page.

Conclusion

In this section, we've explored how to create and display simple pages in Next.js and how to implement navigation between pages using the pages directory and the <Link> component. These are crucial initial steps in building a Next.js application. In the upcoming articles, we'll continue to explore other aspects of Next.js to build dynamic and interactive web applications.