#Search params in Next 15
1 messages · Page 1 of 1 (latest)
Hi @tepid quail. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js 15, you can control which tab is open via URL search parameters (e.g., ?tab=profile). This allows you to share a link that opens the page with a specific tab selected.
How to implement:
-
Update the URL when a tab is clicked:
Use theuseRouter,usePathname, anduseSearchParamshooks in a Client Component to update the search params when a user selects a tab. -
Read the current tab from the URL:
Use theuseSearchParamshook to determine which tab should be active based on the URL.
Example:
'use client'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
const tabs = ['profile', 'settings', 'notifications']
export default function Tabs() {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const currentTab = searchParams.get('tab') || tabs[0]
function handleTabClick(tab: string) {
const params = new URLSearchParams(searchParams.toString())
params.set('tab', tab)
router.push(`${pathname}?${params.toString()}`)
}
return (
<div>
{tabs.map(tab => (
<button
key={tab}
onClick={() => handleTabClick(tab)}
style={{ fontWeight: currentTab === tab ? 'bold' : 'normal' }}
>
{tab}
</button>
))}
<div>
{/* Render content based on currentTab */}
{currentTab === 'profile' && <div>Profile Content</div>}
{currentTab === 'settings' && <div>Settings Content</div>}
{currentTab === 'notifications' && <div>Notifications Content</div>}
</div>
</div>
)
}
- When you click a tab, the URL updates (e.g.,
/your-page?tab=settings). - You can share this URL, and when someone visits it, the correct tab will be open.
References: