Accessing the searchParams from the layout without making it 'use client' #54955
Replies: 6 comments 11 replies
-
Beta Was this translation helpful? Give feedback.
-
|
Go to your nextjs middleware and try something like this: response.headers.set('your value', request.nextUrl.searchParams ||'no value') Then in the component or layout try getting that value you set like this const searchParams = (await headers()).get('yourvalue')|| |
Beta Was this translation helpful? Give feedback.
-
|
Since |
Beta Was this translation helpful? Give feedback.
-
|
Found my self here, Build an App builder and hacking Next.js here's my workaround. Seems scaleable & simple with no side effects. Much ❤️ yall & happy coding. Wishing success upon all devs. layout.tsx |
Beta Was this translation helpful? Give feedback.
-
|
So is there any way we can get the searchParams in root layout.js? |
Beta Was this translation helpful? Give feedback.
-
|
If you need searchParams inside a layout, a simple workaround is to use a parallel route. Parallel routes get searchParams, and since they’re rendered as a ReactNode inside your layout, you can surface the params there without turning the layout into a client component. Example:
export default function RootLayout({ children, params }) {
return (
<html>
<body>
<header>{params}</header>
{children}
</body>
</html>
);
}
export default function ParamsSlot({ searchParams }) {
return <span>{JSON.stringify(searchParams)}</span>;
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I am trying to create an autocomplete component similar to algolia autocomplete but using all the power of react server components, in the way of creating it I base on the searchParams that you can get from a page.tsx so that from my 'use client' input I changed the searchParams with router.push and rendered the items on the server, everything was fine up to there.
The problem came when I wanted to render this Autocomplete component in my root layout to have it in all my pages, since I can't access the searchParams from my layout without doing this 'use client' which in a way ruined my plans since to use my Autocomplete component would have to be added in each of my page.tsx which is not very good.
If you know of a solution to this problem, I would greatly appreciate it.
Beta Was this translation helpful? Give feedback.
All reactions