Tabs Synced with the URL
Medium · Search Params
Tabs kept in useState reset on reload and cannot be linked to. Keep the active tab in the URL instead: /products/1?tab=reviews.
Read it with useSearchParams() and change it with useRouter().push(url). The search params object is read-only, so copy it with new URLSearchParams(searchParams) before changing it.
Update ProductTabs:
- The active tab comes from ?tab=. A missing or unknown value means overview.
- The active tab button has aria-selected="true" (the others "false"), and the tabpanel shows its content.
- Clicking a tab pushes a new URL that keeps all other params. Clicking **Overview** removes tab, because it is the default (/?color=red&tab=specs then Overview gives /?color=red). Other tabs set("tab", id).
- Build the URL from usePathname(): pathname + "?" + query, or just pathname when the query is empty.
Next: Search Box in the URL