#Search params in Next 15

1 messages · Page 1 of 1 (latest)

tepid quail
#

In my Next 15 app, I have a page with tabs. How can i add urlParams so that i can send a link to the page with a specific tab open

crisp voidBOT
#

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:

  1. Update the URL when a tab is clicked:
    Use the useRouter, usePathname, and useSearchParams hooks in a Client Component to update the search params when a user selects a tab.

  2. Read the current tab from the URL:
    Use the useSearchParams hook 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.