React Router v5 Adapter
Using nuqs in React Router v5 applications.
Installation
npx shadcn@latest add @nuqs/adapter-react-router-v5
import { type unstable_AdapterInterface as AdapterInterface, unstable_createAdapterProvider as createAdapterProvider, renderQueryString, type unstable_UpdateUrlFunction as UpdateUrlFunction } from 'nuqs/adapters/custom' import { useCallback, useMemo } from 'react' import { useHistory, useLocation } from 'react-router-dom' function useNuqsReactRouterV5Adapter(): AdapterInterface { const history = useHistory() const location = useLocation() const searchParams = useMemo(() => { return new URLSearchParams(location.search) }, [location.search]) const updateUrl = useCallback<UpdateUrlFunction>( (search, options) => { const queryString = renderQueryString(search) if (options.history === 'push') { history.push({ search: queryString, hash: window.location.hash }) } else { history.replace({ search: queryString, hash: window.location.hash }) } if (options.scroll) { window.scrollTo(0, 0) } }, [history.push, history.replace] ) return { searchParams, updateUrl } } export const NuqsAdapter = createAdapterProvider(useNuqsReactRouterV5Adapter)
Usage
Wrap your <BrowserRouter> with the <NuqsAdapter>:
import { NuqsAdapter } from './nuqs-adapter'
export function ReactRouter() {
return (
<NuqsAdapter>
<BrowserRouter>
<Switch>{/* Your routes here */}</Switch>
</BrowserRouter>
</NuqsAdapter>
)
}Compatibility
This adapter is compatible with nuqs@^2.8: support for react-router-dom@^5
was extended in nuqs@2.8.0, but will likely be removed in nuqs@3.0.0.
If you need support for React Router v5, pin your dependency to nuqs@^2.
The custom adapters APIs are not yet stable and may change in the future in a minor or patch release (not following SemVer).
Use the registry's RSS feed to stay updated on any changes.