๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
React/Nextjs

[Nextjs] searchParams๋กœ URL ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง ํŒŒ์‹ฑํ•˜๊ธฐ

by LasBe 2024. 9. 9.
๋ฐ˜์‘ํ˜•

๐Ÿ“’ searchParam์œผ๋กœ ์ฟผ๋ฆฌ์ŠคํŠธ๋ง ํŒŒ์‹ฑํ•˜๊ธฐ

๋ชจ๋“  ๊ฐ’๋“ค์„ ๊ตณ์ด ์ƒํƒœ๋กœ ๊ด€๋ฆฌํ•  ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.

 

๊ฐ„๋‹จํ•œ ๊ฐ’์„ ์ €์žฅํ•˜๊ฑฐ๋‚˜, ๊ฐ’์„ ์œ ์ง€์‹œํ‚ค๋ฉฐ URL์„ ๊ณต์œ ํ•  ๋•Œ ์ฃผ๋กœ ์ฟผ๋ฆฌ์ŠคํŠธ๋ง์„ ์‚ฌ์šฉํ•˜๋Š”๋ฐ,

์ด๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„  ๋‹ค์Œ๊ณผ ๊ฐ™์ด URL ๋งˆ์ง€๋ง‰์— “?”๋ฅผ ์ถ”๊ฐ€ํ•œ ํ›„ ๋ฐ์ดํ„ฐ๋ฅผ key=value ํ˜•ํƒœ๋กœ ๋‚˜์—ดํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

https://abcd.com?ํ‚ค=๊ฐ’&ํ‚ค2=๊ฐ’2

๊ทธ๋Ÿผ nextjs์—์„œ ์–ด๋–ป๊ฒŒ ์ฟผ๋ฆฌ์ŠคํŠธ๋ง์„ ํŒŒ์‹ฑํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์†Œ๊ฐœํ•ฉ๋‹ˆ๋‹ค.

 

๐Ÿ“Œ Server Component

type SearchParamProps = {
  searchParams: {
    page: number;
    title: string;
  };
};

export default function ServerSearchParam(props: SearchParamProps) {
  const page = props.searchParams.page;
  const title = props.searchParams.title;
  return (
    <div>
      <h1>{JSON.stringify(props)}</h1>
      <h1>{`page -> ${page} / title -> ${title}`}</h1>
    </div>
  );
}

์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ์—๋Š” ์‚ฌ์ „์— ์ •์˜๋œ ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์„ ํ•ด๋‹น ํŽ˜์ด์ง€ props์˜ searchParam ํƒ€์ž…์œผ๋กœ ์ •์˜ํ•ด๋‘๋ฉด ๊ฐ„ํŽธํ•˜๊ฒŒ props.searchParams.key๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๐Ÿ“Œ Client Component

"use client";

import { useSearchParams } from "next/navigation";

export default function ClientSearchParam() {
  const searchParams = useSearchParams();
  const page = searchParams.get("page");
  const title = searchParams.get("title");

  return (
    <div className={style.box}>
      <h1>{`page -> ${page} / title -> ${title}`}</h1>
    </div>
  );
}

ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ์—์„œ๋Š” ๊ฐ„ํŽธํ•˜๊ฒŒ ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์„ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋Š” useSearchParams๋ž€ ํ›…์„ ์ œ๊ณตํ•ด์ค๋‹ˆ๋‹ค.

์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ props๋ฅผ ํ†ตํ•ด ์ฟผ๋ฆฌ ์ŠคํŠธ๋ง์„ ํŒŒ์‹ฑํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ํ›…์˜ ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•ด๋ณด๋Š” ๊ฒƒ๋„ ๋‚˜์˜์ง€ ์•Š์•„๋ณด์ž…๋‹ˆ๋‹ค.

useSearchParams.get() ์œผ๋กœ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋Š” ๊ฒƒ ๋ฟ๋งŒ์ด ์•„๋‹Œ ๋‹ค๋ฅธ ๊ธฐ๋Šฅ๋“ค์„ ํƒ์ƒ‰ํ•˜๊ณ  ์‹ถ์€ ๋ถ„๋“ค๊ป˜์„  ๋‹ค์Œ ๊ณต์‹ ๋ฌธ์„œ๋ฅผ ์ฐธ์กฐํ•ด์ฃผ์„ธ์š”.

https://nextjs.org/docs/app/api-reference/functions/use-search-params

 

Functions: useSearchParams | Next.js

API Reference for the useSearchParams hook.

nextjs.org

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€


์˜คํ”ˆ ์ฑ„ํŒ