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 function that returns the component to be rendered, accepting params and query objects.
      • 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.

Example

import { Router, Route, Link, navigate } from "./routing"

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

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

  return <LoginForm />
}