Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/scottrippey/next-current-route

React Hook for strongly-typed access to the current NextJS route, and for pushing strongly-typed changes
https://github.com/scottrippey/next-current-route

next next-router nextjs nextjs-router react router

Last synced: about 1 month ago
JSON representation

React Hook for strongly-typed access to the current NextJS route, and for pushing strongly-typed changes

Awesome Lists containing this project

README

        

# `next-current-route`
React Hook for reading / writing values to the URL in a NextJS appliication.

This is perfect for features such as deep-linking.

Install via `npm install --save next-current-route`

# API

## useRouteState

This is a replacement for React's `useState`. It reads and writes a value to the current NextJS route.

### Example
```tsx
// pages/example/[id].tsx
import { useRouteState } from 'next-current-route';

type ExampleRoute = { id: string, search?: string };

function Example() {
const [ id, setId ] = useRouteState("id");
const [ search, setSearch ] = useRouteState("search");
return


Search:
setSearch(e.target.value)}
/>
;
}
```

### Usage
```tsx
const [ value, setValue ] = useRouteState(key, method?);
```

- `key: string` - The name of the query parameter
- `method?: 'replace' (default) | 'push' | 'url'`
- `'replace'` (default) - Replaces the current URL with the new one (does not add to history)
- `'push'` - Pushes the new URL to history
- `'url'` - Simply returns a new URL object, which can be used with `next/link`. Example:
```tsx

Link

```
- `value: string` - The value from the current route
- `setValue: string` - Sets the value on the current route
- `TQuery` (optional) - Provides a more specific data type than `string`.
```tsx
type TabRoute = { tab?: 'one' | 'two' | 'three' };
const [ tab, setTab ] = useRouteState("tab");
// tab: undefined | 'one' | 'two' | 'three';
```

## useCurrentRoute

This hook is just like `useRouteState`, but supports reading and writing of **multiple parameters** at the same time.

### Example
```tsx
// pages/example/[id].tsx
type ExampleRouteParams = { id: string, search?: string };

const ExamplePage = () => {
const [ query, route ] = useCurrentRoute();

return


Features



Read strongly-typed values from the current route:
ID: { query.id } Search: { query.search }



Write strongly-typed values to the current route:
route.replace({ search: e.target.value })} />
(replaces the current URL with "example/id?search=...")

route.replace({ search: undefined })}>
Clear Search
(sets the URL back to "example/id")



Works great with "next/link" too:

Go to "example/123"


;
}
```