Routing

Overview

The routing module provides mechanisms for handling client-side navigation within a single-page application (SPA). It enables you to define routes that map URLs to specific components, allowing for seamless transitions between different views without full page reloads.

Key Components

    • Renders a single child component based on the current URL path.
    • Manages navigation history and URL updates.
    • Properties:
      • basePath (optional): A prefix for path matching, useful when the application is deployed in a subdirectory.
    • Defines a path pattern and the associated component to render when the path matches.
    • Properties:
      • element: A JSX element to render.
      • path: A string representing the path pattern to match.
      • fallthrough (optional): A boolean indicating whether to match loosely, allowing nested routers.
    • An anchor tag that handles client-side navigation without full page reloads.
    • Maintains crawlability by providing a valid href attribute for search engines.
    • Properties:
      • to: The destination URL for navigation.
    • A function for programmatic navigation to a given URL.
    • A hook that allows you to access the URL state as parsed by the router.

Example

import { Router, Route, Link, navigate, useRouter } from "kaioken"

function App() {
  return (
    <Router>
      <Route path="/" element={<HomePage />} />
      <Route path="/login" element={<LoginPage />} />
      <Route path="/users/:userId" element={<UserPage />} />
    </Router>
  )
}

function LoginPage() {
  const user = useUser() // some custom hook that gets auth state
  if (user) {
    return navigate("/")
  }

  return <LoginForm />
}

function UserPage() {
  const { params } = useRouter()
  
  /**
   * the ":userId" part of the Route path is parsed from the URL 
   * and made accessible via useRouter()
   */
  return <h1>User: {params.userId}</h1> 
}