Create Pages With Dynamic Routes in Blitz.js

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 4 months ago

Blitz supports pages with dynamic routes. For example, if you create a file called app/pages/posts/[slug].tsx, then it will be accessible at posts/my-first-post, posts/my-second-post, etc.

Example: If you create app/pages/[slug].tsx that exports a React component like below, it will be accessible at /post/you-slug-param.

import { useParams } from "blitz"

const Post = () => {
  const params = useParams()
  return (
      <h1>Post: {params.title}</h1>

export default Post

Using the useParams or useParam hooks provided by blitz to get the dynamic param and use it in your component.

Khaled Garbaya: [0:00] You can also create pages with dynamic routes in Blitz.js. Let's rename this post1 to square brackets and then the parameter name. In this case, we will call it slug and close with a square bracket. Let's stop our server and run it again. In here, if we change this to post2, it will still render the same page. We can type anything after posts here, and it will still show that page.

[0:39] To get this parameter here, we need to use the hook provided by Blitz, which is called useParams. First thing, let's import useParams from Blitz. Second, let's change the shape of our component to allow for hooks. Maybe let's give it a name and don't forget to export it. In here, we will wrap it with curly brackets and return this one.

[1:08] To get the param we simply need to call the hook. We do const params and we call useParams and display that. Since we named this part slug here, this will be available inside of params.slug. Let's display that and save.

[1:32] You can see here it's showing up the parameter that we pass in the URL. If we change it to something else like "Hello world," hit Enter. You can see here, this is the param.