Skip to main content
Dynamic routing is the idea of creating routes that aren’t fixed. For example, leaf’s x.com profile is x.com/leafphp, but yours is x.com/username. Since there’s no real way for X to know what username you’d set, your profile link can’t be hardcoded, and so we call that a dynamic route.

Creating dynamic routes

Hana routes are tied to files, so you might be wondering how we can build a url like /users/id where id is the dynamic part. For cases like that, the file/folder name should be wrapped in [] , so in this case the file name could be made like this:
  • users/[id].tsx -> /users/[id]
  • users/[id]/index.tsx -> /users/[id]
And the dynamic part of the url can be accessed via the useParams() hook:
src/pages/users/[id].tsx
import { useParams } from '@hanabira/router';

export default function User() {
  const { id } = useParams();

  return <div>User ID: {id}</div>
}
Note that the name of the dynamic section is used as the name of the parameter you’ll access through useParams() so each dynamic URL section should be unique.

Nested Dynamic Routes

You can create a dynamic route consisting of more than one dynamic section. For example, you can create a route that accepts a user id and a post id, and for such cases, we can utilize the dynamic section as the folder name.
src/pages/users/[user]/posts/[id].tsx
import { useParams } from '@hanabira/router';

export default function Post() {
  const { user, id } = useParams();

  return (
    <div>
      User: {user}
      <br />
      Post ID: {id}
    </div>
  )
}

Dynamic Routes with Query Parameters

This is not an unusual combination, as query parameters can themselves be used for dynamic routing. We can combine query parameters with dynamic url segments to make urls like this: https://example.com/feed/userid?post=postId
src/pages/feed/[userId].tsx
import { useParams, useQueryParams } from '@hanabira/router';

export default function User() {
  const { userId } = useParams();
  const { post } = useQueryParams();

  return (
    <div>
      User ID: {id}
      <br />
      Post: {post}
    </div>
  )
}

Optional Dynamic Routes

Optional dynamic routes are dynamic routes that can be accessed with or without a parameter. This can be done by wrapping the parameter in double square brackets ([[]]). For example, if you create a file called [[query]].tsx in the pages/search directory, it will create a route for /search/[[query]]. This route will be accessible on /search and /search/:query. You can then access the query parameter using the useParams hook.
src/pages/search/[[query]].tsx
import { useParams } from '@hanabira/router';

export default function Search() {
  const { query } = useParams();

  return <div>Query: {query ?? 'nothing'}</div>
}