@route-weaver/react
Version:
React hooks for @route-weaver/core
208 lines (146 loc) • 6.87 kB
Markdown
# @route-weaver/react
[](https://badge.fury.io/js/%40route-weaver%2Freact)
[](https://opensource.org/licenses/MIT)
The official React integration for `route-weaver`. It provides a set of custom Hooks for seamless integration with your React applications, making it easy to access navigation data and functions with full typesafety.
## Why @route-weaver/react?
Tired of string-based routing leading to runtime errors, broken links, and a frustrating developer experience? Traditional React routing libraries often leave you vulnerable to typos in route paths and mismatches in parameters, issues that typically only surface in the browser.
`@route-weaver/react` solves this by bringing end-to-end typesafety to your routing. By defining your routes as a structured, typed object, you unlock a new level of confidence and productivity. This library doesn't just manage routes; it creates a contract between your route definitions and your components, ensuring that any attempt to navigate to a non-existent route or pass incorrect parameters is caught by TypeScript at build time, not by your users at runtime.
## Installation
```bash
npm install @route-weaver/core @route-weaver/react
```
## Setup
Wrap your application with the `RouteWeaverProvider` and provide it with your `navInstance` and `weaver` instances.
```tsx
// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { createRouteWeaver } from '@route-weaver/core';
import { RouteWeaverProvider } from '@route-weaver/react';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
const routeWeaver = createRouteWeaver({
home: { label: 'Home', path: '/' },
users: {
label: 'Users',
path: 'users',
children: {
view: { label: 'View User', path: ':id' },
},
},
});
const navInstance = routeWeaver.build({
main: ['home', 'users'],
});
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Router>
<RouteWeaverProvider navInstance={navInstance} weaver={routeWeaver}>
<App />
</RouteWeaverProvider>
</Router>
</React.StrictMode>
);
```
## Expanded API Reference
### `useNavigation(groupName)`
* **Why and When to Use**: Use this hook to get a specific navigation group you defined in `routeWeaver.build()`. It's perfect for rendering navigation menus, lists of links, or any UI element that corresponds to a predefined set of routes.
* **`groupName`**: The name of the navigation group to retrieve (e.g., `'main'`).
* **Returns**: An array of `StructuredNavItem` objects for the specified group.
**Practical Example**:
```tsx
import { useNavigation } from '@route-weaver/react';
import { Link } from 'react-router-dom';
function Header() {
const mainNav = useNavigation('main');
return (
<nav>
{mainNav.map(item => (
<Link key={item.id} to={item.fullPath}>
{item.label}
</Link>
))}
</nav>
);
}
```
---
### `useActiveRoute()`
* **Why and When to Use**: Use this hook to get the currently active route based on the URL. This is essential for highlighting the active link in a navigation menu, displaying the title of the current page, or fetching data specific to the current route.
* **Returns**: An `ActiveRoute` object (`{ route, params }`) or `undefined`.
**Practical Example**:
```tsx
import { useActiveRoute } from '@route-weaver/react';
function PageTitle() {
const activeRoute = useActiveRoute();
if (!activeRoute) {
return <h1>404 - Page Not Found</h1>;
}
return <h1>{activeRoute.route.label}</h1>;
}
```
---
### `useBreadcrumbs()`
* **Why and When to Use**: Use this hook to generate a breadcrumb trail for the current page. It helps users understand their location within your application's hierarchy and provides easy navigation back to parent pages.
* **Returns**: An array of `StructuredNavItem` objects representing the path to the active route.
**Practical Example**:
```tsx
import { useBreadcrumbs } from '@route-weaver/react';
import { Link } from 'react-router-dom';
function Breadcrumbs() {
const crumbs = useBreadcrumbs();
return (
<nav>
{crumbs.map((crumb, index) => (
<span key={crumb.id}>
<Link to={crumb.fullPath}>{crumb.label}</Link>
{index < crumbs.length - 1 && ' > '}
</span>
))}
</nav>
);
}
```
---
### `useBuildPath()`
* **Why and When to Use**: This is the cornerstone of typesafe navigation. Use this hook to get the `buildPath` function, which allows you to construct URLs in a completely typesafe way. It eliminates the risk of typos in paths or parameters, as TypeScript will validate everything at compile time.
* **Returns**: The `buildPath(routeId, params)` function from the core `routeWeaver` instance.
**Practical Example**:
```tsx
import { useBuildPath } from '@route-weaver/react';
import { Link } from 'react-router-dom';
function UserProfileLink({ userId }: { userId: string }) {
const buildPath = useBuildPath();
const profilePath = buildPath('users.view', { id: userId });
return <Link to={profilePath}>View Profile</Link>;
}
```
## Before and After: The Typesafety Advantage
### Before: Manual and Error-Prone
Without `route-weaver`, you might build links with string interpolation, a common source of bugs.
```tsx
// If the route changes from '/users/:id' to '/profile/:id', this link will break silently.
const profilePath = `/users/${userId}`;
```
This is fragile. There's no guarantee `/users/:id` is a valid route, and refactoring is a nightmare.
### After: Typesafe and Confident
With `route-weaver`, `useBuildPath` gives you full typesafety and autocompletion.
```tsx
import { useBuildPath } from '@route-weaver/react';
const buildPath = useBuildPath();
// ✅ Correct: TS knows 'users.view' is a valid route and 'id' is a required param.
const profilePath = buildPath('users.view', { id: '123' });
// ❌ Compile-Time Error: 'userId' is not a valid parameter name.
// const invalidPath = buildPath('users.view', { userId: '123' });
// ❌ Compile-Time Error: 'post' is not a defined route.
// const nonExistentPath = buildPath('post', { id: '123' });
```
This immediate feedback prevents bugs and makes refactoring safe and predictable.
## Live Examples
Explore interactive examples on CodeSandbox to see `@route-weaver/react` in action.
* **Basic Setup**: [Link to CodeSandbox](https://codesandbox.io/p/sandbox/route-weaver-react-example-w7t7x6)
* **Advanced Usage with Authorization**: [Link to CodeSandbox] (coming soon)
## Contributing
Contributions are welcome! Please see the main [CONTRIBUTING.md](../../CONTRIBUTING.md) file for details.
## License
MIT