Building Apps with Cuppa Router
Learn how to build single-page applications with declarative routing using the Cuppa Router package.
•Cuppa Team
tutorialrouterspa
The @mycuppa/router package provides a powerful, type-safe routing solution for your Cuppa applications. In this post, we'll explore how to build a simple multi-page application.
Setting Up Routes
First, install the router package:
npm install @mycuppa/router
Define your routes using the declarative API:
import { createRouter, Route } from '@mycuppa/router'
const router = createRouter([
{
path: '/',
component: HomePage,
},
{
path: '/about',
component: AboutPage,
},
{
path: '/posts/:id',
component: PostPage,
},
])
Navigation
Navigate between pages using the Link component or programmatic navigation:
import { Link, useNavigate } from '@mycuppa/router'
function Navigation() {
const navigate = useNavigate()
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<button onClick={() => navigate('/posts/1')}>
View Post 1
</button>
</nav>
)
}
Route Parameters
Access route parameters using the useParams hook:
import { useParams } from '@mycuppa/router'
function PostPage() {
const { id } = useParams<{ id: string }>()
return (
<div>
<h1>Post {id}</h1>
{/* Fetch and display post content */}
</div>
)
}
Nested Routes
Cuppa Router supports nested routes for complex layouts:
const router = createRouter([
{
path: '/dashboard',
component: DashboardLayout,
children: [
{
path: 'overview',
component: OverviewPage,
},
{
path: 'analytics',
component: AnalyticsPage,
},
],
},
])
Try It Out
Check out our Blog App Example to see Cuppa Router in action!
For more details, visit the Router documentation.