Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useParams() #47373

Merged
merged 2 commits into from
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions packages/next/src/client/components/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useContext, useMemo } from 'react'
import type { FlightRouterState } from '../../server/app-render/types'
import {
AppRouterContext,
GlobalLayoutRouterContext,
LayoutRouterContext,
} from '../../shared/lib/app-router-context'
import {
Expand Down Expand Up @@ -132,7 +133,41 @@ export function useRouter(): import('../../shared/lib/app-router-context').AppRo
return router
}

interface Params {
[key: string]: string
}
// TODO-APP: handle parallel routes
function getSelectedParams(
tree: FlightRouterState,
params: Params = {}
): Params {
// After first parallel route prefer children, if there's no children pick the first parallel route.
const parallelRoutes = tree[1]
const node = parallelRoutes.children ?? Object.values(parallelRoutes)[0]

if (!node) return params
const segment = node[0]
const isDynamicParameter = Array.isArray(segment)
const segmentValue = isDynamicParameter ? segment[1] : segment
if (!segmentValue || segmentValue === '__PAGE__') return params

if (isDynamicParameter) {
params[segment[0]] = segment[1]
}

return getSelectedParams(node, params)
}

export function useParams() {
clientHookInServerComponentError('useParams')
const { tree } = useContext(GlobalLayoutRouterContext)
return getSelectedParams(tree)
}

// TODO-APP: handle parallel routes
/**
* Get the canonical parameters from the current level to the leaf node.
*/
function getSelectedLayoutSegmentPath(
tree: FlightRouterState,
parallelRouteKey: string,
Expand Down
11 changes: 11 additions & 0 deletions test/e2e/app-dir/use-params/app/[id]/[id2]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use client'
import { useParams } from 'next/navigation'
export default function Page() {
const { id, id2 } = useParams()
return (
<div>
<div id="param-id">{id}</div>
<div id="param-id2">{id2}</div>
</div>
)
}
10 changes: 10 additions & 0 deletions test/e2e/app-dir/use-params/app/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use client'
import { useParams } from 'next/navigation'
export default function Page() {
const { id } = useParams()
return (
<div>
<div id="param-id">{id}</div>
</div>
)
}
7 changes: 7 additions & 0 deletions test/e2e/app-dir/use-params/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
18 changes: 18 additions & 0 deletions test/e2e/app-dir/use-params/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Link from 'next/link'

export default function Page() {
return (
<>
<div>
<Link href="/a" id="to-a">
To /a
</Link>
</div>
<div>
<Link href="/a/b" id="to-a-b">
To /a/b
</Link>
</div>
</>
)
}
8 changes: 8 additions & 0 deletions test/e2e/app-dir/use-params/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: { appDir: true },
}

module.exports = nextConfig
24 changes: 24 additions & 0 deletions test/e2e/app-dir/use-params/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"plugins": [
{
"name": "next"
}
]
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
40 changes: 40 additions & 0 deletions test/e2e/app-dir/use-params/use-params.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { createNextDescribe } from 'e2e-utils'

createNextDescribe(
'use-params',
{
files: __dirname,
},
({ next }) => {
it('should work for single dynamic param', async () => {
const $ = await next.render$('/a/b')
expect($('#param-id').text()).toBe('a')
})
it('should work for nested dynamic params', async () => {
const $ = await next.render$('/a/b')
expect($('#param-id').text()).toBe('a')
expect($('#param-id2').text()).toBe('b')
})

it('should work for single dynamic param client navigating', async () => {
const browser = await next.browser('/')
expect(
await browser
.elementByCss('#to-a')
.click()
.waitForElementByCss('#param-id')
.text()
).toBe('a')
})

it('should work for nested dynamic params client navigating', async () => {
const browser = await next.browser('/')
await browser
.elementByCss('#to-a-b')
.click()
.waitForElementByCss('#param-id')
expect(await browser.elementByCss('#param-id').text()).toBe('a')
expect(await browser.elementByCss('#param-id2').text()).toBe('b')
})
}
)