I am using Next Js in my application. I know that we can create dynamic pages using pages
folder, but i can not create a certain design for pages structure.
What i want to achieve: I need to have the next paths in my application: /user/pageAccordingUserIdWhichIsDymamicPage/userDataWhichIsStaticPage/anotherDynamicPage
.
My question is, how the folder structure should look?
Note: all paths are related to user, so i expect that the pages should be located in one page folder from pages
.
This is possible using a feature known as dynamic routing. For more information see: https://nextjs.org/docs/routing/dynamic-routes .
For each dynamic route/url you wish to create follow the process below:
For example: "/users/roger/data" would be split to [users, roger, data].
For each section of the URL, create a folder with the corresponding name. If a certain part of the URL is dynamic, the name of the folder should be wrapped in square brackets- [dynamicData]
.
Finally, create as many index.js
files as you need. These files should be placed in the folders you created.
For example, if you wanted the page /users/roger to work - you would go to your pages directory, users, roger, and put an index.js file there. Remember - that if you want 'roger' to be dynamic, you would create a dynamic folder like
[userName]
instead of roger.
You could then access the dynamic properties in each index.js file by acceding the router's query property. For example:
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const {userId, dynamic} = router.query
return <p>
userId: {userId} <br />
dynamic: {dynamic}
</p>
}
export default Post
You would obviously replace the {userId, dynamic}
with the names you chose for the dynamic routes (ie - the names of the folders).
(Example adapted from the link above)
In Next.js your route endpoints are defined by the file name thus making it quick and easy to create a new route.
Now let's say that you want to create a route like this "/profile/:id" with id being your custom parameter.
To create a file with a custom parameter just surround your custom parameter with brackets like this [id]
You can also use the three dot syntax (like this [...id]) to accept infinite unspecified dynamic pages.
I would suggest watching the video linked down below which really helped me get started with Next.js.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.