Next.js is a popular framework for developing React applications, and one of its outstanding features is its automatic routing system. With Next.js, you can easily create different pages for your application without needing additional configurations. In this article, we will explore how to define and use routes using the App Router in Next.js.
To begin, you need to create a file in a directory called 'pages' in your project. The file name you choose will correspond to the URL address. For instance, if you have a file named about.js
, this page will automatically be accessible at /about
. This feature greatly simplifies your application's structure, making it very clean and organized.
A key aspect of software development is understanding how routes work along with parameters. Next.js also allows for dynamic routing, which means you can create files with names like [id].js
, corresponding to a parameter in the route.
Another notable feature is using the _app.js
file, which is used for global styling across all pages. This file allows you to apply changes at the application level for all pages, such as adding a global layout or a consistent style.
You can also use the component Link
from the next/link
library to easily navigate between different pages. Next.js allows you to create dynamic links and breadcrumbs that are SEO friendly and fast.
Finally, if you need a complex routing system, you can use the API for dynamic routes. This API allows you to create routes and controls that exceed basic functionalities, making them highly efficient in more extensive and complex projects.
Sample Code:
// linking between different pages
import Link from 'next/link';
function HomePage() {
return (
<div>
<h1>Welcome to our site</h1>
<Link href="/about">
<a>About Us</a>
</Link>
</div>
);
}
export default HomePage;
Code Line Explanation:
import Link from 'next/link';
In this line, we import the
Link
component from the next/link
library, which is used for routing between pages.function HomePage() { ... }
This line creates a React component named
HomePage
that displays the main page content.<div></div>
This element includes the content inside the component.
<h1>Welcome to our site</h1>
This line includes a main title with welcome text for users.
<Link href="/about"><a>About Us</a></Link>
This line creates a link to the
/about
page that leads users to another page.export default HomePage;
This line exports the
HomePage
component as the default for this module.