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 (
<div>
<h1>Post: {params.title}</h1>
</div>
)
}
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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!