I'm using Next js. I want to use dynamic routing based on this documentation. How can I set two parameters like href="/page/[p1]/[p2]" to the Link component? What should be the structure of my page file and how use the router.query?
-
What have you tried so far?hurricane– hurricane2019-09-24 08:11:09 +00:00Commented Sep 24, 2019 at 8:11
-
I used a wildcard and a query string like page/[p1]?p2=... , but I want use 2 wildcard. Also use this structure for my page name [p1][p2].tsxelyas.m– elyas.m2019-09-24 08:16:31 +00:00Commented Sep 24, 2019 at 8:16
-
1Check this github.com/zeit/next.js/tree/canary/examples/dynamic-routinghurricane– hurricane2019-09-24 08:23:55 +00:00Commented Sep 24, 2019 at 8:23
-
Thanks, Its a good exampleelyas.m– elyas.m2019-09-24 08:29:04 +00:00Commented Sep 24, 2019 at 8:29
5 Answers
Folder structure should be Like that
Page - Folder
blog - Folder Name
[p1] - Folder Name
[p2].js - File Name
it will work when you call URL like /blog/postname/id it will call p2.js page
1 Comment
You can do this with the help of dynamic routing in nextjs 9.
For example, pages/post/[postId]/[commentId].js would match /post/p1/c1. Its query object would be: { postId: 'p1', commentId: 'c1' }.
your Link component should be like this:
<Link
href="/post/[postId]/[commentId]"
as={`/post/${postId}/${commentId}`}>
<a>link to comment</a>
</Link>
3 Comments
pages directory look like when doing this?[postId] folder and [postId].js file if I wanted to handle both top-level and bottom-level pages, and indeed it works like thatThe folder structure in your nextjs projects should look like this
📂user
┗ 📂[user-id]
┗ 📂 posts
┗ [post-id]
this will generate url paths for you like below, which is widely used format
/users/[id]/posts/[postId]
You can follow these guidelines to structure your urls: https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/#h-nesting-resources-for-hierarchical-objects
In summary, formats like "/pages/p1/p2", do not really tell a whole lot of information what sub-resources you are choosing and are considered less readable.
Comments
Other method is create a slug [...slug] and get the parameters with router.query.
1 Comment
Folder structure like this will work
-[blog] //folder name
-[post].js //file name
-items //folder name
-[category] //folder name
-[subCategory].js //file name
you can simply call the blog and post like
<a href="/blog/post"></a>
you can simply call the category and subcategory like
<a href="/items/category/subCategory"></a>