Back to articles
Basics of Routing in NextJS
Hey there! Today, we're going to talk about routing in Next.js, one of the most popular frameworks for building React applications.
Routing is essential in any web application as it helps to navigate from one page to another. With Next.js, we have a lot of options when it comes to routing. Let's dive into it!
Basics of Routing in Next.js
In Next.js, routing is based on the file system. When you create a new page, it automatically generates a route based on the file name. For example, if you create a file named about.js in the pages directory, Next.js will generate a route to http://localhost:3000/about.
To create a link to this page, you can use the Link component from the next/link module, like so:
import Link from 'next/link'
function AboutPage() {
return (
<div>
<h1>About Page</h1>
<Link href="/">
<a>Home</a>
</Link>
</div>
)
}
export default AboutPage
In this example, we import the Link component and use it to create a link to the home page (/). When the user clicks on the link, Next.js will handle the navigation without reloading the page, giving your users a seamless experience.
Dynamic Routes in Next.js
Next.js also provides support for dynamic routes. Dynamic routes allow you to create pages with URLs that depend on external data. For example, if you have a blog with multiple posts, you can create a dynamic route for each post, like /posts/1, /posts/2, etc.
To create a dynamic route in Next.js, you need to create a file with square brackets ([]) in the pages directory. For example, if you create a file named [slug].js, Next.js will generate a route to http://localhost:3000/[slug].
Here's an example of how to create a dynamic route in Next.js:
function BlogPost({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
)
}
export async function getStaticPaths() {
const res = await fetch('https://myapi.com/posts')
const posts = await res.json()
const paths = posts.map(post => ({
params: { slug: post.slug }
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const res = await fetch('https://myapi.com/posts/' + params.slug)
const post = await res.json()
return { props: { post } }
}
export default BlogPost
In this example, we create a dynamic route for blog posts. We fetch the list of posts from an API using getStaticPaths, and map the posts to an array of paths. We then use getStaticProps to fetch the post data for a specific slug, and pass it to the BlogPost component as props.
Routing is an essential part of any web application, and Next.js makes it easy to create dynamic and responsive routes. By leveraging the power of the file system and React components, you can create a seamless user experience that keeps your users engaged and coming back for more.
I hope you found this article helpful in understanding routing in Next.js. Happy coding!