0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js AppRouterを利用して、searchparamsを取得する

Last updated at Posted at 2024-11-14

0. 環境

name version
nextjs 15.0

1. 取得方法

upgrading/version-15に記載があった。

1-1. pageレベルで、asyncを利用。

app/index.tsx
type Params = Promise<{ slug: string }>
type SearchParams = Promise<{ [key: string]: string | string[] | undefined }>

const RootPage = async ({ params, searchParams }:{ props: Params, searchParams: SearchParams }) => {
    const p = await params
    const q = await searchParams
    return (
        <div>
            <div>{ JSON.stringify(p) }</div>
            <div>{ JSON.stringify(q) }</div>
        </div>
    )
}

export default RootPage

1-2. useを利用する

app/index.tsx
import { use } from "react"

type Params = Promise<{ slug: string }>
type SearchParams = Promise<{ [key: string]: string | string[] | undefined }>

const RootPage = (props: { props: Params, searchParams: SearchParams }) => {
    const p = use(props.params)
    const q = use(props.searachParams)
    return (
        <div>
            <div>{ JSON.stringify(p) }</div>
            <div>{ JSON.stringify(q) }</div>
        </div>
    )
}

export default RootPage

1-3. FCを利用して型情報を記載する

app/index.tsx
import { type FC } from "react"

type RootPageProps {
    params: Promise<{ [key: string]: string }>
    searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}

const RootPage = async ({ params, searchParams }:{ props: Params, searchParams: SearchParams }) => {
    const p = await params
    const q = await searchParams
    return (
        <div>
            <div>{ JSON.stringify(p) }</div>
            <div>{ JSON.stringify(q) }</div>
        </div>
    )
}

export default RootPage
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?