next.js routing

datajcthemax·2023년 6월 14일

next js

목록 보기
7/10

Next.js is a React framework that provides capabilities for server-side rendering and generating static websites for React-based web applications. One of its key features is file-system based routing.

In Next.js, routing is based on the file system, so you don't need to set up a routing configuration as you would in many other React frameworks.

Here's how it works:

  • For the most basic routing, you create a .js file under the pages directory, and the file path corresponds to the route path. For example, if you create a file named about.js in the pages directory, your application will then have a route /about that will render the component you export from that file.

  • For nested routes, you can create a directory under pages. For example, if you want a route like /user/profile, you create a user directory under pages and then put a profile.js file in the user directory.

  • For dynamic routes, you use the square bracket [] syntax to denote a dynamic part of the route. For example, if you have a blog and want to have routes for individual blog posts, you can create a file like pages/post/[id].js, and then you will have routes like /post/1, /post/2, etc. The part inside the brackets is a parameter that you can access within your component.

  • Catch all routes can be defined using ... inside the brackets. For example, a file named pages/post/[...id].js will match /post/a, /post/a/b, /post/a/b/c and so on.

Next.js also provides the Link and useRouter hooks from the next/router package for programmatic navigation.

Here is an example of how to use Link for navigation:

import Link from 'next/link'

function Navigation() {
  return (
    <nav>
      <Link href="/">
        <a>Home</a>
      </Link>
      <Link href="/about">
        <a>About</a>
      </Link>
    </nav>
  )
}

export default Navigation

And here is an example of how to use the useRouter hook to access the router instance:

import { useRouter } from 'next/router'

function Post({ post }) {
  const router = useRouter()

  const { id } = router.query

  // render logic here
}

In this example, id would be the dynamic part of the route in /post/[id].

0개의 댓글