Skip to content

Commit 9212378

Browse files
committed
feat: add useLink hook
1 parent ec5f7b5 commit 9212378

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,21 @@ import { Route } from 'atomic-router-react'
7878

7979
<Route route={homeRoute} view={HomePage} />
8080
```
81+
82+
### `useLink` — resolve path from route
83+
84+
```tsx
85+
import { useLink } from 'atomic-router-react'
86+
import { createRoute } from 'atomic-router'
87+
88+
// example path: /some/route/:someId
89+
const someRoute = createRoute<{ someId: number }>()
90+
91+
function SomeComponent() {
92+
const path = useLink(someRoute, { someId: 1 })
93+
// -> /some/route/1
94+
}
95+
```
96+
97+
Be sure, route is passed into `routes` for `createHistoryRoutes`.
98+
Else hook will throw `[useLink] Route not found`.

src/index.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ export * from './route';
33
export * from './router-provider';
44
export * from './create-route-view';
55
export * from './create-routes-view';
6+
export * from './use-link'

src/use-link.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { buildPath, RouteInstance, RouteParams, RouteQuery } from "atomic-router";
2+
import { useRouter } from "./router-provider";
3+
4+
export function useLink<T extends RouteParams>(
5+
route: RouteInstance<T>,
6+
params: T,
7+
query: RouteQuery = {},
8+
): string {
9+
const router = useRouter()
10+
const routeObj = router.routes.find((routeObj) => routeObj.route === route);
11+
12+
if (!routeObj) {
13+
throw new Error(`[useLink] Route not found. Maybe it is not passed into createHistoryRouter`)
14+
}
15+
16+
return buildPath({
17+
pathCreator: routeObj.path,
18+
params: params,
19+
query: query,
20+
})
21+
}

0 commit comments

Comments
 (0)