Accessing search Params from Layout or Component File in Next.JS 13
Asked Answered
F

4

13

I want to access the search params in a Component or in Layout File to get the lang. There is an way to do that? I Read that is impossible to get the searchparams in Layout File, but there is any other way in Next.JS 13? Or other way to get the lang inside the component?

export default function DashboardLayout({ children }: DashboardProps) {
    return (
        <html>
            <body>
                <div className="w-full h-full flex absolute bg-slate-100">
                    <div className="flex flex-col">
                        <div className="bg-sky-800 w-[20rem] h-12 flex items-center justify-center">
                            <img src="/bigLogo.svg" className="w-28 h-12" title="ProPay" alt="ProPay" />
                        </div>
                        <div className="bg-white h-full shadow-md">
                            <DashboardMenu />
                        </div>
                    </div>
                    <div className="flex flex-col w-full">
                        <div className="bg-sky-700 flex justify-between items-center h-12 pr-5">
                            <p className="ml-5 text-lg text-white">Câmara Municipal de Tondela</p>
                            <SelectLang />
                        </div>
                        <div className="p-3">
                            {children}
                        </div>
                    </div>
                </div>
            </body>
        </html>
    )
};

.

export default function DashboardMenu(){
    const lang: DashboardLangsTypes = getLang("en", "dashboard"); // i want the lang here
    return (
...
Frigging answered 27/3, 2023 at 22:49 Comment(1)
Did you find a solution because I Look into the same issueBookmaker
S
9

This is not documented but the Layout component actually receives 2 properties children and params, so you can simply read the params property

interface DashboardProps {
  children: React.ReactNode;
  params: { id: string }
}

export default function DashboardLayout({ children, params }: DashboardProps) {
  console.log(params.id)
  ...
}

According to the documentation

Layouts are Server Components by default but can be set to a Client Component.

So it's technically possible to read the params using the Client Component hook useParams. I would not recommend using it as you will need to transform your Layout Component into a Client Component (with the use client directive).

Shalne answered 30/12, 2023 at 2:18 Comment(1)
I think the question is how to get search params, not url params.Impacted
H
1

you can use router to get the lang as parameter and then pass it down as props to your components

  const router = useRouter();
  const lang = router.query.lang;

to import it :

import { useRouter } from "next/router";

in your case :

import { useRouter } from "next/router";

export default function DashboardLayout({ children }: DashboardProps) {
  const router = useRouter();
  const lang = router.query.lang;

  return (
    ....
  );
}
Horsefaced answered 27/3, 2023 at 22:56 Comment(5)
Hi, thanks for try to help. I receive this error, but i don't want to render this at client. ReactServerComponentsError: You have a Server Component that imports next/router. Use next/navigation instead. Maybe one of these should be marked as a client entry "use client": ./src\app\dashboard\layout.tsx The next/navigation don't have useRouter() queryDemoralize
okay let me get this clear you want to pass the lang from DashboardLayout to DashboardMenu component ?Horsefaced
The lang is in the url, if I can get it from the Layout or directly from the component, whatever. Because I easily send the layout data to the component. I just want to access data in the url.Demoralize
i will add another answer so it is more clearHorsefaced
Note that this will only work for client-side componentsStoops
D
0

Helo, if you gonna use a client side component then you can use useSearchParams Hook available in the version 13..

Here is the beta documentation link

'use client';

export default function ExampleClientComponent() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams()!;

  // Get a new searchParams string by merging the current
  // searchParams with a provided key/value pair
  const createQueryString = useCallback(
    (name: string, value: string) => {
      const params = new URLSearchParams(searchParams);
      params.set(name, value);

      return params.toString();
    },
    [searchParams],
  );

  return (
    <>
      <p>Sort By</p>

      {/* using useRouter */}
      <button
        onClick={() => {
          // <pathname>?sort=asc
          router.push(pathname + '?' + createQueryString('sort', 'asc'));
        }}
      >
        ASC
      </button>

      {/* using <Link> */}
      <Link
        href={
          // <pathname>?sort=desc
          pathname + '?' + createQueryString('sort', 'desc')
        }
      >
        DESC
      </Link>
    </>
  );
}

Happy coding

Delaware answered 14/4, 2023 at 21:20 Comment(0)
S
0

Use the useParams hooks exported from next/navigation.

Sector answered 27/10, 2023 at 15:8 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Route

© 2022 - 2024 — McMap. All rights reserved.