Reputation: 1
I'm fairly new to nextjs 13, especially with the app router, I have a very big project in react that I would like to migrate and I know it won't be an easy road, I've started to tackle a bit of the future challenges, starting with routing.
I will have a lot of routes, but for now let's focus on one, we will call it "section", and the path will be something like : /:section?/:subsection?
Routing with nextjs has always been kind of mystical to me, I know react-router really well but not the folder logic by the nextjs team.
I know typical routing in nextjs is folder directed, like app/section/page.tsx
, app/about/[id]
etc
Thing is, I don't know these things in my case, because they are fully dynamical, I've searched in the nextjs doc but could not find an easy answer.
My ideal project folder will be something like src/app/section/page.tsx
, src/app/post/page.tsx
, etc
I have gone the path of rewrites, in the next-config.js
file, but I can't make it work.
I can retrieve the query params in the main page, through the props given by nextjs, but I can't retrieve it in a client component through any of the hooks.
I have done a codesanbox of course, to give you a reproducing code.
To reproduce, navigate to an url like /one/two
, and look at both the browser and node console.
The repo: https://codesandbox.io/p/sandbox/brave-dew-sh75dc
Everything in the description
Upvotes: 0
Views: 1215
Reputation: 4946
Next.js uses file-based router. Here are some solution for your routing cases in the question and the comments:
To make a dynamic route, you can use [slug]
format in folder name. It can be nested at any level of nesting. You can make src/app/[section]/[subscription]/page.tsx
You can then read the section
and subscription
values in page.js (as well as layout.js) via the props:
// src/app/[section]/[subscription]/page.tsx
export default function Page({params}) {
const {sectionl, subscription} = params;
}
Or in Client Components via useParams
hook:
'use client'
import { useParams } from 'next/navigation'
export default function ExampleClientComponent() {
const params = useParams<{ section: string; subscription: string }>()
}
You can also, use useSelectedLayoutSegment
and useSelectedLayoutSegments
in Client Components under layout.
To read the query params e.g. ?id=123
in a page.js you can use the prop searchParams
export default function Page({ searchParams }) {
const id = searchParams.id;
}
Or using useSearchParams
in ClientComponents:
'use client'
import { useSearchParams } from 'next/navigation'
export default function ExampleClientComponent() {
const searchParams = useSearchParams();
const id = searchParams.get("id");
}
To implement /:section/:subsection/:slug(.*)-id([0-9]*)
You could make src/app/[section]/[subscription]/[slug]/page.js
with Self-healing URL.
This Blog explains Self-healing URLs very well:
Upvotes: 0