1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Create Files And Directories For Dynamic Routes as a nextjs til

This commit is contained in:
jbranchaud
2021-01-23 17:06:37 -06:00
parent 56cd253433
commit cd79989c99
2 changed files with 44 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_1022 TILs and counting..._
_1023 TILs and counting..._
---
@@ -461,6 +461,7 @@ _1022 TILs and counting..._
### Next.js
- [Create Files And Directories For Dynamic Routes](nextjs/create-files-and-directories-for-dynamic-routes.md)
- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md)
- [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md)

View File

@@ -0,0 +1,42 @@
# Create Files And Directories For Dynamic Routes
[Next.js](https://nextjs.org/) allows you to go beyond static, predefined pages
and routes with [dynamic
routing](https://nextjs.org/docs/routing/dynamic-routes).
The common example is a `posts` route that includes a _slug_ to dynmically
reference a particular post. The template for that page can be defined at
`pages/posts/[slug].js`. Notice the square brackets around the slug, that tells
Next that it is a dynamic route and whatever matches against the slug should be
included in `router.query` as `slug`.
Let's try to create that file:
```bash
$ touch pages/posts/[slug].js
zsh: no matches found: pages/posts/[slug].js
```
That failed. To create this kind of file from the command-line, you are going
to need to escape the square brackets:
```bash
$ touch pages/posts/\[slug\].js
```
You can do the same if you use dynamic routing in your directory structure:
```bash
$ mkdir -p pages/posts/\[year\]/\[month\]/\[day\]
```
And now we have the following structure:
```bash
$ exa --tree pages/posts
pages/posts
├── [slug].js
└── [year]
└── [month]
└── [day]
```