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.
- replace (optional, default
false
): A boolean indicating whether to replace the current history entry. - inherit (optional, default
false
): If true, links prepend thepath
of parent routes andbasePath
of parent routers.
-
- A function for programmatic navigation to a given URL.
-
- A hook that allows you to access the URL
params
andquery
objects as parsed by the router. Also providessetQuery
, to update the query string in the URL.
- A hook that allows you to access the URL
Example
import { Router, Route, Link } from "kaioken"
import { LoginPage } from "./LoginPage"
import { UserList } from "./UserList"
import { UserPage } from "./UserPage"
function App() {
return (
<>
<nav>
<Link to="/">Home</Link>
<Link to="/login">Login</Link>
<Link to="/users">Users</Link>
</nav>
<Router>
<Route path="/" element={<h1>Home</h1>} />
<Route path="/login" element={<LoginPage />} />
<Route path="/users" element={<UserList />} />
<Route path="/users/:userId" element={<UserPage />} />
</Router>
</>
)
}