### Install Wouter Source: https://github.com/molefrog/wouter/blob/v3/README.md Install Wouter using npm. For Preact projects, use the specific preact package. ```bash npm i wouter ``` -------------------------------- ### Bun Test Example Source: https://github.com/molefrog/wouter/blob/v3/CLAUDE.md A basic test case using Bun's built-in testing framework. ```typescript import { test, expect } from "bun:test"; test("hello world", () => { expect(1).toBe(1); }); ``` -------------------------------- ### Run Bun Server with Hot Reload Source: https://github.com/molefrog/wouter/blob/v3/CLAUDE.md Command to start the Bun server with hot module replacement enabled. ```sh bun --hot ./index.ts ``` -------------------------------- ### Basic Wouter App Example Source: https://github.com/molefrog/wouter/blob/v3/README.md A simple demo app demonstrating basic routing with Link, Route, and Switch components. It includes nested routes and parameter extraction. ```jsx import { Link, Route, Switch } from "wouter"; const App = () => ( <> Profile About Us {/* Routes below are matched exclusively - the first matched route gets rendered */} {(params) => <>Hello, {params.name}!} {/* Default route in a switch */} 404: No such page! ); ``` -------------------------------- ### Nested Routing Example Source: https://github.com/molefrog/wouter/blob/v3/README.md Illustrates how to use the `nest` prop on Route components to create nested routing contexts, where child routes match relative to the parent path. ```javascript ``` -------------------------------- ### Testing Navigation and Redirects with memoryLocation Source: https://github.com/molefrog/wouter/blob/v3/README.md Configure `memoryLocation` to record navigation history and use its `navigate` function for external navigation. This example demonstrates testing a redirect. ```jsx it("performs a redirect", () => { const { hook, history, navigate } = memoryLocation({ path: "/", // will store navigation history in `history` record: true, }); const { container } = render( Index Orders ); expect(history).toStrictEqual(["/"]); navigate("/unknown/route"); expect(container.innerHTML).toBe("Orders"); expect(history).toStrictEqual(["/", "/unknown/route", "/orders"]); }); ``` -------------------------------- ### Server-Side Rendering with Wouter Router Source: https://github.com/molefrog/wouter/blob/v3/README.md Configure Wouter for server-side rendering by wrapping your app with `Router` and providing `ssrPath` and `ssrSearch` props. This example shows how to handle redirects during SSR. ```javascript import { renderToString } from "react-dom/server"; import { Router } from "wouter"; const handleRequest = (req, res) => { // top-level Router is mandatory in SSR mode // pass an optional context object to handle redirects on the server const ssrContext = {}; const prerendered = renderToString( ); if (ssrContext.redirectTo) { // encountered redirect res.redirect(ssrContext.redirectTo); } else { // respond with prerendered html } }; ``` -------------------------------- ### Custom Router Configuration with useHashLocation Source: https://github.com/molefrog/wouter/blob/v3/README.md Configure Wouter's routing behavior with the Router component. This example demonstrates using a custom hook, useHashLocation, for hash-based routing and setting a base path. ```jsx import { useHashLocation } from "wouter/use-hash-location"; {/* Your app goes here */} ; ``` -------------------------------- ### Customizing Location Hook with Router Source: https://github.com/molefrog/wouter/blob/v3/README.md Wrap your application in a `Router` component to customize the location hook. This example shows how to use `useHashLocation` for hash-based routing. ```javascript import { Router, Route } from "wouter"; import { useHashLocation } from "wouter/use-hash-location"; const App = () => ( ... ); ``` -------------------------------- ### Exclusive Route Rendering with Switch Source: https://github.com/molefrog/wouter/blob/v3/README.md Illustrates how the Switch component renders only the first matching Route, ensuring exclusive routing behavior. Includes an example of a fallback route. ```javascript import { Route, Switch } from "wouter"; {/* in wouter, any Route with empty path is considered always active. This can be used to achieve "default" route behaviour within Switch. Note: the order matters! See examples below. */} This is rendered when nothing above has matched ``` -------------------------------- ### Implement Strict Routes with Custom Parser Source: https://github.com/molefrog/wouter/blob/v3/README.md Configure Wouter to enforce strict route matching, including trailing slashes, by providing a custom parser function to the `` component. This example uses `path-to-regexp` to achieve strict routing. ```javascript import { pathToRegexp } from "path-to-regexp"; /** * Custom parser based on `pathToRegexp` with strict route option */ const strictParser = (path, loose) => { const keys = []; const pattern = pathToRegexp(path, keys, { strict: true, end: !loose }); return { pattern, // `pathToRegexp` returns some metadata about the keys, // we want to strip it to just an array of keys keys: keys.map((k) => k.name), }; }; const App = () => ( ... ... ); ``` -------------------------------- ### Getting Current Location and Navigating with useLocation Source: https://github.com/molefrog/wouter/blob/v3/README.md Use `useLocation` to access the current path and a navigation function. The component re-renders when the location changes, and `navigate` updates the path. ```javascript import { useLocation } from "wouter"; const CurrentLocation = () => { const [location, navigate] = useLocation(); return (
{`The current page is: ${location}`} navigate("/somewhere")}>Click to update
); }; ``` -------------------------------- ### Getting Current Search String with useSearch Source: https://github.com/molefrog/wouter/blob/v3/README.md The `useSearch` hook retrieves the current query string without the leading '?'. It triggers a re-render only when the search string itself changes. ```jsx import { useSearch } from "wouter"; // returns "tab=settings&id=1" const searchString = useSearch(); ``` -------------------------------- ### Managing Search Parameters with useSearchParams Source: https://github.com/molefrog/wouter/blob/v3/README.md Use `useSearchParams` to get a `URLSearchParams` object and a function to update it. You can update parameters by providing new values, a callback function, or by replacing all parameters. ```jsx import { useSearchParams } from 'wouter'; const [searchParams, setSearchParams] = useSearchParams(); // extract a specific search parameter const id = searchParams.get('id'); // modify a specific search parameter setSearchParams((prev) => { prev.set('tab', 'settings'); return prev; }); // override all search parameters setSearchParams({ id: 1234, tab: 'settings', }); // by default, setSearchParams() will push a new history entry // to avoid this, set `replace` option to `true` setSearchParams( (prev) => { prev.set('order', 'desc'); return prev; }, { replace: true, }, ); // you can also pass a history state in options setSearchParams( (prev) => { prev.set('foo', 'bar'); return prev; }, { state: 'hello', }, ); ``` -------------------------------- ### Opt-in View Transitions with Link Component Source: https://github.com/molefrog/wouter/blob/v3/specs/view-transitions-spec.md Demonstrates how to opt-in to view transitions for specific navigation events using the `transition` prop on the Wouter `` component. ```jsx // In your component Home ; ``` -------------------------------- ### Opt-in View Transitions Programmatically Source: https://github.com/molefrog/wouter/blob/v3/specs/view-transitions-spec.md Shows how to trigger view transitions programmatically by passing the `transition: true` option to Wouter's `navigate` function. ```javascript const [location, navigate] = useLocation(); navigate("/", { transition: true }); ``` -------------------------------- ### Using Wouter with Preact Source: https://github.com/molefrog/wouter/blob/v3/README.md Shows the import statement difference when using Wouter with Preact, requiring 'wouter-preact' instead of the standard 'wouter' package. ```diff - import { useRoute, Route, Switch } from "wouter"; + import { useRoute, Route, Switch } from "wouter-preact"; ``` -------------------------------- ### Selective View Transitions with Wouter Source: https://github.com/molefrog/wouter/blob/v3/README.md Illustrates how to enable View Transitions API selectively for specific links or programmatic navigations using the 'transition' prop within Wouter. ```jsx // Enable transition for a specific link About // Or programmatically const [location, navigate] = useLocation(); navigate("/about", { transition: true }); // Then check for it in your handler const aroundNav: AroundNavHandler = (navigate, to, options) => { if (!document.startViewTransition) { navigate(to, options); return; } if (options?.transition) { document.startViewTransition(() => { flushSync(() => { navigate(to, options); }); }); } else { navigate(to, options); } }; ``` -------------------------------- ### Bun Server with HTML Imports Source: https://github.com/molefrog/wouter/blob/v3/CLAUDE.md A Bun server that serves HTML and supports hot module replacement for development. It includes basic routing and optional WebSocket support. ```typescript import index from "./index.html" Bun.serve({ routes: { "/": index, "/api/users/:id": { GET: (req) => { return new Response(JSON.stringify({ id: req.params.id })); }, }, }, // optional websocket support websocket: { open: (ws) => { ws.send("Hello, world!"); }, message: (ws, message) => { ws.send(message); }, close: (ws) => { // handle close } }, development: { hmr: true, console: true, } }) ``` -------------------------------- ### Declaring Routes with Different Styles Source: https://github.com/molefrog/wouter/blob/v3/README.md Demonstrates three ways to define a Route component: simple form, render-prop style, and using the component prop. ```javascript import { Route } from "wouter"; // simple form // render-prop style {params => } // the `params` prop will be passed down to ``` -------------------------------- ### Integrating Wouter with View Transitions API Source: https://github.com/molefrog/wouter/blob/v3/README.md Shows how to integrate Wouter with the View Transitions API by creating a custom aroundNav handler that uses document.startViewTransition and flushSync for synchronous DOM rendering. ```jsx import { flushSync } from "react-dom"; import { Router, type AroundNavHandler } from "wouter"; const aroundNav: AroundNavHandler = (navigate, to, options) => { // Check if View Transitions API is supported if (!document.startViewTransition) { navigate(to, options); return; } document.startViewTransition(() => { flushSync(() => { navigate(to, options); }); }); }; const App = () => ( {/* Your routes here */} ); ``` -------------------------------- ### Using Link with a Custom Component (asChild) Source: https://github.com/molefrog/wouter/blob/v3/README.md Demonstrates how to use the `asChild` prop with the Link component to render a custom component that acts as a navigation link. The custom component must implement an `onClick` handler. ```jsx // use this instead // Remember, `UIKitLink` must implement an `onClick` handler // in order for navigation to work! ``` -------------------------------- ### Extracting Wildcard Parameters with useRoute Source: https://github.com/molefrog/wouter/blob/v3/README.md Demonstrates how to extract parameters from wildcard segments using `useRoute`. The parameter name for wildcards is `"*"`. ```javascript // wildcards, matches "/app", "/app-1", "/app/home" const [match, params] = useRoute("/app*"); if (match) { // "/home" for "/app/home" const page = params["*"]; } ``` -------------------------------- ### Using Bare Location Hooks for Minimalist Routing Source: https://github.com/molefrog/wouter/blob/v3/README.md For minimal bundle size, use bare location hooks like `useBrowserLocation`. Manually match the current location to render specific routes. ```js import { useBrowserLocation } from "wouter/use-browser-location"; const UsersRoute = () => { const [location] = useBrowserLocation(); if (location !== "/users") return null; // render the route }; ``` -------------------------------- ### Basic HTML Structure Source: https://github.com/molefrog/wouter/blob/v3/CLAUDE.md A simple HTML file that imports a JavaScript module for frontend logic. ```html

Hello, world!

``` -------------------------------- ### Testing Query Parameters with memoryLocation Source: https://github.com/molefrog/wouter/blob/v3/README.md Use `memoryLocation` to test routes with query parameters. Wouter automatically handles `useSearch()` when `memoryLocation` is provided as the hook. ```jsx it("works with query parameters", () => { const { hook } = memoryLocation({ path: "/products?sort=price&order=asc" }); const { result } = renderHook(() => useSearch(), { wrapper: ({ children }) => {children}, }); expect(result.current).toBe("sort=price&order=asc"); }); ``` -------------------------------- ### useRoute Pattern Cheatsheet Source: https://github.com/molefrog/wouter/blob/v3/README.md Illustrates various pattern syntaxes supported by `useRoute`, including named segments, optional parameters, suffixes, wildcards, and regex. ```javascript useRoute("/app/:page"); useRoute("/app/:page/:section"); // optional parameter, matches "/en/home" and "/home" useRoute("/:locale?/home"); // suffixes useRoute("/movies/:title.(mp4|mov)"); // wildcards, matches "/app", "/app-1", "/app/home" useRoute("/app*"); // optional wildcards, matches "/orders", "/orders/" // and "/orders/completed/list" useRoute("/orders/*?"); // regex for matching complex patterns, // matches "/hello:123" useRoute(/^[/]([a-z]+):([0-9]+)[/]?$/); // and with named capture groups useRoute(/^[/](?[a-z]+):(?[0-9]+)[/]?$/); ``` -------------------------------- ### Testing Specific Routes with memoryLocation Source: https://github.com/molefrog/wouter/blob/v3/README.md Configure Wouter for testing by using `memoryLocation` to provide a fixture for the current location. The `static` option prevents navigation changes. ```jsx import { render } from "@testing-library/react"; import { memoryLocation } from "wouter/memory-location"; it("renders a user page", () => { // `static` option makes it immutable // even if you call `navigate` somewhere in the app location won't change const { hook, searchHook } = memoryLocation({ path: "/user/2", static: true }); const { container } = render( {(params) => <>User ID: {params.id}} ); expect(container.innerHTML).toBe("User ID: 2"); }); ``` -------------------------------- ### Navigating to Absolute Paths with Nested Routes Source: https://github.com/molefrog/wouter/blob/v3/README.md Demonstrates using the `~` prefix within a `Link` component to navigate to a top-level absolute path from within a nested routing context. ```javascript Back to Home ``` -------------------------------- ### Create a Default/404 Route with Switch Source: https://github.com/molefrog/wouter/blob/v3/README.md Implement a fallback route for 404 Not Found pages by placing a default `` as the last child of a `` component. This route will match if no other routes are satisfied. ```jsx import { Switch, Route } from "wouter"; ... 404, Not Found! ``` ```jsx ... {/* will match anything that starts with /users/, e.g. /users/foo, /users/1/edit etc. */} ... {/* will match everything else */} {(params) => `404, Sorry the page ${params["*"]} does not exist!`} ``` -------------------------------- ### SSR Path and Search Equivalence Source: https://github.com/molefrog/wouter/blob/v3/README.md Demonstrates that Wouter can automatically parse search parameters from the `ssrPath` if it contains a '?'. ```jsx ; // is the same as ; ``` -------------------------------- ### Routing Hooks Source: https://github.com/molefrog/wouter/blob/v3/README.md Core hooks imported from 'wouter' for routing logic, parameter extraction, and search string access. ```APIDOC ## Routing Hooks ### `useRoute` #### Description Determines if the current page matches a given pattern. ### `useLocation` #### Description Manipulates the current router's location, subscribing to the browser location by default. This is distinct from `useBrowserLocation`. ### `useParams` #### Description Returns an object containing parameters matched from the closest route. ### `useSearch` #### Description Returns the search string, which is everything after the '?' in the URL. ### `useRouter` #### Description Returns the global router object, useful for advanced configuration and customization. Use only when necessary. ``` -------------------------------- ### Specify Base Path for Subfolder Deployment Source: https://github.com/molefrog/wouter/blob/v3/README.md Use the `` component to configure a base path when deploying your application to a subfolder. This ensures links and routes are correctly scoped. ```jsx import { Router, Route, Link } from "wouter"; const App = () => ( {/* the link's href attribute will be "/app/users" */} Users The current path is /app/users! ); ``` ```jsx Path is /app/cms/users! ``` -------------------------------- ### Basic Link Component Usage Source: https://github.com/molefrog/wouter/blob/v3/README.md Shows the basic usage of the Link component for navigation, including its `href` and `to` props, and proxying standard `a` tag attributes. ```javascript import { Link } from "wouter" Home // `to` is an alias for `href` Home // all standard `a` props are proxied Home // all location hook options are supported ``` -------------------------------- ### TypeScript Types for Wouter View Transitions Source: https://github.com/molefrog/wouter/blob/v3/specs/view-transitions-spec.md Illustrates the TypeScript types provided by Wouter for view transitions, including `NavigateOptions` which incorporates the `transition` property, and the `AroundNavHandler` type for custom navigation wrappers. ```typescript import type { NavigateOptions, AroundNavHandler } from "wouter"; // NavigateOptions already includes transition const navigate = (to: string, options?: NavigateOptions) => { // options.transition is available // options.replace is available // options.state is available }; // AroundNavHandler type for the aroundNav callback const aroundNav: AroundNavHandler = (navigate, to, options) => { if (options?.transition) { // handle transition } navigate(to, options); }; ``` -------------------------------- ### Animated Route Transitions with AnimatePresence (Workaround) Source: https://github.com/molefrog/wouter/blob/v3/README.md Provides a workaround for animating route transitions with Wouter and framer-motion by using useRoute to conditionally render the animated element as a direct child of AnimatePresence. ```jsx export const MyComponent = ({ isVisible }) => { const [isMatch] = useRoute("/"); return ( {isMatch && ( )} ); }; ``` -------------------------------- ### Navigation with replace and state options Source: https://github.com/molefrog/wouter/blob/v3/README.md The `navigate` function from `useLocation` accepts optional parameters to control navigation behavior. Use `replace: true` to modify the current history entry instead of adding a new one. ```jsx const [location, navigate] = useLocation(); navigate("/jobs"); // `pushState` is used navigate("/home", { replace: true }); // `replaceState` is used ``` -------------------------------- ### Explicit Arguments for View Transitions Wrapper Source: https://github.com/molefrog/wouter/blob/v3/specs/view-transitions-spec.md An alternative implementation for the `aroundNav` function that explicitly defines the `to` and `options` arguments for the navigate function, ensuring compatibility with Wouter's routing. ```javascript function aroundNav(navigate, to, options) { if (!document.startViewTransition) { navigate(to, options); return; } document.startViewTransition(() => { flushSync(() => { navigate(to, options); }); }); } ``` -------------------------------- ### Custom Link Wrapper with useRoute Hook Source: https://github.com/molefrog/wouter/blob/v3/README.md Create a custom `` wrapper to control additional props like `style` or `aria-current` based on the active route status. It utilizes the `useRoute` hook to determine if the link's `href` matches the current location. ```javascript const [isActive] = useRoute(props.href); return ( {props.children} ); ``` -------------------------------- ### Styling Active Links with a Function Source: https://github.com/molefrog/wouter/blob/v3/README.md Shows how to use a function for the `className` prop on a Link component to dynamically apply styles based on whether the link is active for the current route. ```jsx (active ? "active" : "")}>Nav ``` -------------------------------- ### Granular Control View Transitions Wrapper Source: https://github.com/molefrog/wouter/blob/v3/specs/view-transitions-spec.md This `aroundNav` implementation provides granular control, only enabling view transitions when the `options?.transition` flag is explicitly set to true. It includes feature detection and uses `flushSync` for synchronous DOM updates. ```javascript import { flushSync } from "react-dom"; function aroundNav(navigate, to, options) { // Feature detection if (!document.startViewTransition) { navigate(to, options); return; } // Only use transitions when explicitly requested if (options?.transition) { document.startViewTransition(() => { flushSync(() => { navigate(to, options); }); }); } else { navigate(to, options); } } ``` -------------------------------- ### Using SSR Search Parameter Source: https://github.com/molefrog/wouter/blob/v3/README.md For Server-Side Rendering, pass the `ssrSearch` prop to the `Router` component to provide the initial search string. ```jsx {/* SSR! */} ``` -------------------------------- ### Animated Route Transitions with AnimatePresence (Incorrect Usage) Source: https://github.com/molefrog/wouter/blob/v3/README.md Demonstrates an incorrect way to use AnimatePresence with Wouter routes, where the animated element is not a direct child of AnimatePresence. ```jsx import { motion, AnimatePresence } from "framer-motion"; export const MyComponent = () => ( {/* This will not work! `motion.div` is not a direct child */} ); ``` -------------------------------- ### Route Matching with useRoute Source: https://github.com/molefrog/wouter/blob/v3/README.md Use `useRoute` to check if the current location matches a pattern and extract parameters. It's powered by `regexparam` for flexible pattern matching. ```javascript import { useRoute } from "wouter"; const Users = () => { // `match` is a boolean const [match, params] = useRoute("/users/:name"); if (match) { return <>Hello, {params.name}!; } else { return null; } }; ``` -------------------------------- ### Components Source: https://github.com/molefrog/wouter/blob/v3/README.md Component-based API elements for building traditional routing interfaces, including links, routes, and switches. ```APIDOC ## Components ### `` #### Description Conditionally renders a component based on a provided pattern. ### `` #### Description Wraps an `` tag to enable navigation within the application. ### `` #### Description Ensures that only the first matched route within its scope is rendered, providing exclusive routing. ### `` #### Description When rendered, this component immediately performs a navigation to a specified path. ### `` #### Description An optional top-level component used for advanced routing configurations, such as setting base paths or custom match functions. #### Props - `hook` (hook): The location hook to use. - `matcher` (matchFn): A custom matching function. - `base` (basePath): The base path for routing. ``` -------------------------------- ### Programmatic Navigation Outside Components Source: https://github.com/molefrog/wouter/blob/v3/README.md Initiate navigation programmatically from outside of React components by importing and using the `navigate` function from `"wouter/use-browser-location"`. This function mirrors the internal navigation logic. ```javascript import { navigate } from "wouter/use-browser-location"; navigate("/", { replace: true }); ``` -------------------------------- ### React Frontend Component Source: https://github.com/molefrog/wouter/blob/v3/CLAUDE.md A React component that imports CSS and renders a heading. It's designed to be used with Bun's frontend capabilities. ```tsx import React from "react"; // import .css files directly and it works import './index.css'; import { createRoot } from "react-dom/client"; const root = createRoot(document.body); export default function Frontend() { return

Hello, world!

; } root.render(); ``` -------------------------------- ### Relative Links and Nested Routes Source: https://github.com/molefrog/wouter/blob/v3/README.md Enable relative routing and linking within your application by using the `nest` prop on a `` component. This creates a nesting context where links are resolved relative to the parent route's path. ```jsx const App = () => ( {/* the href is "/app/dashboard/users" */} {/* Here `useLocation()` returns "/users"! */} ); ``` -------------------------------- ### Enable View Transitions by Default in Wouter Source: https://github.com/molefrog/wouter/blob/v3/specs/view-transitions-spec.md This snippet shows how to wrap Wouter's navigate function to enable view transitions by default. It includes feature detection for older browsers and uses `flushSync` for synchronous DOM updates. ```javascript import { flushSync } from "react-dom"; function aroundNav(navigate, ...navArgs) { // Feature detection for older browsers if (!document.startViewTransition) { navigate(...navArgs); return; } document.startViewTransition(() => { flushSync(() => { navigate(...navArgs); }); }); } ; ``` -------------------------------- ### Programmatic Navigation with useLocation Source: https://github.com/molefrog/wouter/blob/v3/README.md For more complex navigation logic, such as triggering redirects from event handlers, use the useLocation hook. This allows direct control over navigation using the setLocation function. ```javascript import { useLocation } from "wouter"; const [location, setLocation] = useLocation(); fetchOrders().then((orders) => { setOrders(orders); setLocation("/app/orders"); }); ``` -------------------------------- ### useParams Source: https://github.com/molefrog/wouter/blob/v3/README.md Accesses parameters exposed through matching dynamic segments in the route. It allows components to retrieve route parameters without prop drilling. ```APIDOC ## useParams ### Description This hook allows you to access the parameters exposed through matching dynamic segments. It provides access to route parameters within the `Route` component, avoiding prop drilling. ### Usage Import `useParams` from 'wouter' and call it within your component. ### Example (Dynamic Segments) ```javascript import { Route, useParams } from "wouter"; const User = () => { const params = useParams(); // Access parameter by name: params.id // Access parameter by index: params[0] }; ``` ### Example (Regex Paths) ```javascript import { Route, useParams } from "wouter"; const User = () => { const params = useParams(); // Access parameter by name: params.id // Access parameter by index: params[0] }; [0-9]+)[/]?$/} component={User} /> ``` ``` -------------------------------- ### useRouter Source: https://github.com/molefrog/wouter/blob/v3/README.md Provides access to the global router object, which holds routing options configured in the `Router` component. Useful for advanced integrations like custom location hooks. ```APIDOC ## useRouter ### Description If you're building advanced integrations, such as custom location hooks, you might want to get access to the global router object. The router is a simple object that holds routing options configured in the `Router` component. ### Usage Import `useRouter` from 'wouter' and call it within your component. ### Example ```js import { useRouter, Router } from "wouter"; const Custom = () => { const router = useRouter(); // Access router properties router.hook; // `useBrowserLocation` by default router.base; // e.g., "/app" }; const App = () => ( ); ``` ``` -------------------------------- ### Accessing Router Object with useRouter Source: https://github.com/molefrog/wouter/blob/v3/README.md The `useRouter` hook provides access to the global router object, which holds configuration options like the base path and the location hook. ```javascript import { useRouter } from "wouter"; const Custom = () => { const router = useRouter(); router.hook; // `useBrowserLocation` by default router.base; // "/app" }; const App = () => ( ); ``` -------------------------------- ### Declarative Redirect Component Source: https://github.com/molefrog/wouter/blob/v3/README.md Use the Redirect component for simple, declarative redirects. It can accept a 'to' path and optional state or replace props for navigation customization. ```jsx ``` ```jsx // arbitrary state object ``` ```jsx // use `replaceState` ``` -------------------------------- ### useRoute Hook Source: https://github.com/molefrog/wouter/blob/v3/README.md The `useRoute` hook checks if the current location matches a provided pattern and returns an object containing matched parameters. It supports various segment types including named parameters, optional parameters, suffixes, wildcards, and regular expressions. ```APIDOC ## `useRoute` Hook ### Description Checks if the current location matches the pattern provided and returns an object with parameters. This hook is powered by the `regexparam` library, supporting its full pattern syntax. ### Usage ```js import { useRoute } from "wouter"; const Users = () => { const [match, params] = useRoute("/users/:name"); if (match) { return <>Hello, {params.name}!; } return null; }; ``` ### Supported Patterns - **Named Parameters**: `useRoute("/app/:page")` - **Optional Parameters**: `useRoute("/:locale?/home")` - **Suffixes**: `useRoute("/movies/:title.(mp4|mov)")` - **Wildcards**: `useRoute("/app*")` - **Optional Wildcards**: `useRoute("/orders/*?")` - **Regular Expressions**: `useRoute(/^[/]([a-z]+):([0-9]+)[/]?$/)` - **Named Capture Groups**: `useRoute(/^[/](?[a-z]+):(?[0-9]+)[/]?$/)` ### Wildcard Parameters For wildcard segments, the parameter name is `"*"`. ```js const [match, params] = useRoute("/app*"); if (match) { // "/home" for "/app/home" const page = params["*"]; } ``` ``` -------------------------------- ### Custom Navigation Wrapper Source: https://github.com/molefrog/wouter/blob/v3/README.md Implement custom logic around navigation calls using the 'aroundNav' option in the Router. This allows intercepting navigation to perform actions before or after the navigation occurs. ```javascript const aroundNav = (navigate, to, options) => { // do something before navigation navigate(to, options); // perform navigation // do something after navigation }; ``` -------------------------------- ### Client-Side Hydration with Wouter Router Source: https://github.com/molefrog/wouter/blob/v3/README.md Hydrate your Wouter application on the client to make it interactive. Ensure the client-side JSX matches the server-rendered JSX to avoid hydration warnings. ```javascript import { hydrateRoot } from "react-dom/client"; const root = hydrateRoot( domNode, // during hydration, `ssrPath` is set to `location.pathname`, // `ssrSearch` set to `location.search` accordingly // so there is no need to explicitly specify them ); ``` -------------------------------- ### Extracting Route Parameters with useParams Source: https://github.com/molefrog/wouter/blob/v3/README.md Use `useParams` to access parameters from dynamic segments in your route paths. It works with both string and regex paths, allowing access by name or index. ```javascript import { Route, useParams } from "wouter"; const User = () => { const params = useParams(); params.id; // "1" // alternatively, use the index to access the prop params[0]; // "1" }; /> ``` ```javascript import { Route, useParams } from "wouter"; const User = () => { const params = useParams(); params.id; // "1" params[0]; // "1" }; [0-9]+)[/]?$/} component={User}> /> ``` -------------------------------- ### useLocation Hook Source: https://github.com/molefrog/wouter/blob/v3/README.md The `useLocation` hook provides the current path and a navigation function. It allows components to re-render when the location changes and to programmatically update the URL and history. ```APIDOC ## `useLocation` Hook ### Description To get the current path and navigate between pages, call the `useLocation` hook. It returns a value (the current location) and a setter function (`navigate`). The component will re-render when the location changes, and calling `navigate` updates the location and performs navigation. By default, it uses `useBrowserLocation`. It also returns a scoped path when used within nested routes or with a base path setting. ### Usage ```js import { useLocation } from "wouter"; const CurrentLocation = () => { const [location, navigate] = useLocation(); return (
); }; ``` ### Additional Navigation Parameters The `navigate` function accepts an optional second argument, an object with parameters to control navigation: - **`replace`** (boolean): If `true`, modifies the current history entry instead of adding a new one (uses `replaceState`). - **`state`** (any): An object to update `history.state` during navigation. #### Examples ```jsx const [location, navigate] = useLocation(); navigate("/jobs"); // Uses `pushState` by default navigate("/home", { replace: true }); // Uses `replaceState` navigate("/home", { state: { modal: "promo" } }); // Updates history.state ``` ### Customizing the Location Hook To customize the location hook (e.g., use hash-based routing), wrap your app in a `Router` component and provide a custom `hook` prop. ```js import { Router, Route } from "wouter"; import { useHashLocation } from "wouter/use-hash-location"; const App = () => ( {/* ... other routes */} ); ``` ``` -------------------------------- ### Link Component Source: https://github.com/molefrog/wouter/blob/v3/README.md The Link component renders an anchor (``) tag that handles navigation when clicked. It supports standard `a` tag props and location hook options. It can also wrap children using the `asChild` prop. ```APIDOC ## Link Component ### Description Link component renders an `` element that, when clicked, performs a navigation. ### Method Component ### Endpoint N/A (Component API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (Link specific) - **href** (string) - Required - The URL to navigate to. Alias for `to`. - **to** (string) - Required - The URL to navigate to. Alias for `href`. - **asChild** (boolean) - Optional - If true, wraps children in an `` tag without rendering an `` tag itself. - **className** (string | function) - Optional - CSS class name. If a function, it receives an `active` boolean. - **replace** (boolean) - Optional - If true, replaces the current history entry. - **state** (object) - Optional - State to be passed to the history entry. ### Request Example ```jsx import { Link } from "wouter" Home // `to` is an alias for `href` Home // all standard `a` props are proxied Home // all location hook options are supported // using asChild // styling active links (active ? "active" : "")}>Nav ``` ### Response N/A (Component API) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Location Hooks Source: https://github.com/molefrog/wouter/blob/v3/README.md Standalone hooks for managing browser or hash locations, similar to useState. They can be used with a Router for advanced features. ```APIDOC ## Location Hooks ### `useBrowserLocation` #### Description Allows manipulation of the current browser location using the History API. #### Import `import { useBrowserLocation } from "wouter/use-browser-location";` ### `useHashLocation` #### Description Manages location based on the hash part of the URL (the string after '#'). #### Import `import { useHashLocation } from "wouter/use-hash-location";` ### `memoryLocation` #### Description An in-memory location hook with history support, external navigation, and an immutable mode suitable for testing. #### Import `import { memoryLocation } from "wouter/memory-location";` #### Note This is a higher-order hook. See testing examples for usage. ``` -------------------------------- ### Route Component Source: https://github.com/molefrog/wouter/blob/v3/README.md The Route component renders UI conditionally based on a path pattern. It supports simple forms, render-prop styles, and component props. It also supports route nesting with the `nest` prop. ```APIDOC ## Route Component ### Description `Route` represents a piece of the app that is rendered conditionally based on a pattern `path`. Pattern has the same syntax as the argument you pass to [`useRoute`](#useroute-route-matching-and-parameters). The library provides multiple ways to declare a route's body: ### Method Component ### Endpoint N/A (Component API) ### Parameters #### Path Parameters - **path** (string) - Optional - The URL path pattern to match. - **component** (React.ComponentType) - Optional - A component to render when the route matches. - **nest** (boolean) - Optional - Enables nested routing context. #### Query Parameters None #### Request Body None ### Request Example ```jsx // simple form // render-prop style {params => } // the `params` prop will be passed down to // Route nesting example ``` ### Response N/A (Component API) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Updating History State with navigate Source: https://github.com/molefrog/wouter/blob/v3/README.md You can provide a `state` option to the `navigate` function to update `history.state` during navigation. ```jsx navigate("/home", { state: { modal: "promo" } }); history.state; // { modal: "promo" } ``` -------------------------------- ### Switch Component Source: https://github.com/molefrog/wouter/blob/v3/README.md The Switch component ensures that only the first matching Route within it is rendered. It's used for exclusive routing scenarios. ```APIDOC ## Switch Component ### Description There are cases when you want to have an exclusive routing: to make sure that only one route is rendered at the time, even if the routes have patterns that overlap. That's what `Switch` does: it only renders **the first matching route**. ### Method Component ### Endpoint N/A (Component API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```jsx import { Route, Switch } from "wouter"; {/* in wouter, any Route with empty path is considered always active. This can be used to achieve "default" route behaviour within Switch. Note: the order matters! See examples below. */} This is rendered when nothing above has matched ; ``` ### Response N/A (Component API) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### useSearch Source: https://github.com/molefrog/wouter/blob/v3/README.md Retrieves the current search (query) string value. The component re-renders only when the search string itself updates. The returned string does not include the leading '?' character. ```APIDOC ## useSearch ### Description Use this hook to get the current search (query) string value. It ensures your component re-renders only when the search string itself changes, not the full location. ### Usage Import `useSearch` from 'wouter' and call it within your component. ### Example ```jsx import { useSearch } from "wouter"; // returns "tab=settings&id=1" const searchString = useSearch(); ``` ### Server-Side Rendering For SSR, use the `ssrSearch` prop passed to the `Router` component. ```jsx {/* SSR! */} ``` ``` -------------------------------- ### Style Active Links with a Function Source: https://github.com/molefrog/wouter/blob/v3/README.md Conditionally apply CSS classes to a `` component based on whether it matches the current route. This uses a function for the `className` prop that receives an `active` boolean. ```jsx (active ? "active" : "")}>Nav link ``` -------------------------------- ### useSearchParams Source: https://github.com/molefrog/wouter/blob/v3/README.md Provides a URLSearchParams object and a setter function to update search parameters. The setter can accept values or a callback function for updating. ```APIDOC ## useSearchParams ### Description Returns a `URLSearchParams` object and a setter function to update search parameters. The setter function can accept a value (object, URLSearchParams, string[][], etc.) or a callback function that receives the current params and returns the new params. ### Usage Import `useSearchParams` from 'wouter' and destructure the returned array. ### Example (Extracting and Modifying) ```jsx import { useSearchParams } from 'wouter'; const [searchParams, setSearchParams] = useSearchParams(); // Extract a specific search parameter const id = searchParams.get('id'); // Modify a specific search parameter using a callback setSearchParams((prev) => { prev.set('tab', 'settings'); return prev; }); // Override all search parameters setSearchParams({ id: 1234, tab: 'settings', }); ``` ### Example (History Management) By default, `setSearchParams()` pushes a new history entry. Use the `replace` option to avoid this. ```jsx // Avoid pushing a new history entry setSearchParams( (prev) => { prev.set('order', 'desc'); return prev; }, { replace: true }, ); // Pass history state in options setSearchParams( (prev) => { prev.set('foo', 'bar'); return prev; }, { state: 'hello' }, ); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.