I am building a Next.js 13 project with the /app
directory. In the root layout, I have a permanent navbar component in which the component is imported from /components/Navbar.jsx
. Inside the Navbar.jsx
, I want to be able to access the slug parameter in url, for example, localhost:3000/:slug
, in which I want the slug id. I have already defined a Next.js 13 page.jsx for that slug. But how do I get the slug id in the navbar component? I also don't want to use window.location.pathname
because it doesn't change when the page routes to a different slug and only does when I refresh.
I have tried the old Next.js 12 method:
//components/navbar.jsx;
import { useRouter } from "next/navigation";
export default function Navbar () {
const router = useRouter();
const { slug } = router.query;
useEffect(() => {
console.log(slug);
}, []);
return <p>Slug: {slug}</p>
}
However it does not work.
(/blog/1)
(/blog?postId=123)
(/blog/1?postId=123)
useParams()
'use client'
import { useParams } from 'next/navigation'
export default function ExampleClientComponent() {
const params = useParams()
// Route -> /shop/[tag]/[item]
// URL -> /shop/shoes/nike-air-max-97
// `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
console.log(params)
return <></>
}
useSearchParams()
'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchBar() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
// URL -> `/dashboard?search=my-project`
// `search` -> 'my-project'
return <>Search: {search}</>
}
any
type'use client'
export default function BlogPost(props: any) {
// URL -> blog/a/b?param1=IamfirstParam¶m2=IamsecondParam
return <div>{props}</div>;
// Output ->
//{
// params: { blogId: [ 'a', 'b' ] },
// searchParams: { param1: 'IamfirstParam', param2: 'IamsecondParam' }
//}
}
defined
type'use client';
// URL -> blog/a/b?param1=IamfirstParam¶m2=IamsecondParam
export default function BlogPost({
params,
searchParams,
}: {
params: { blogId: string[] };
searchParams: { param1: string; param2: string };
}) {
return (
<div>
{params.blogId[0]}
{params.blogId[1]}
{searchParams.param1}
{searchParams.param2}
</div>
);
}
For all possibility of dynamic params refer: How to do dynamic routes with Next.js 13?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With