Client-side routing extension for HTMX
npm install htmx-client-routes
A lightweight HTMX extension for handling client-side routes and mocking server responses.
Useful for prototyping, testing, or adding custom frontend logic before hitting the server.
- Define client-side routes directly in the frontend
- Return custom responses without a backend
- Intercept HTMX requests and perform extra logic before sending them to the server
- Great for prototyping or mocking APIs
``bash`
npm install htmx-client-routes
`html`
or
`html`
`html
$3
`typescript
import htmx from 'htmx.org';
import htmxClientRoutes, { addRoute } from 'htmx-client-routes';// Initialize the extension
htmxClientRoutes.init();
// Define your routes
addRoute('/hello', '
Hello World!
');addRoute('/users/{id}', ({ params }) => {
return
;
});// You can also use async handlers
addRoute('/api/data', async ({ params }) => {
const response = await fetch(
/api/data?id=${params.id});
const data = await response.json();
return ${JSON.stringify(data, null, 2)};
});
`React Integration
You can use React components with htmx-client-routes by importing the React integration module:
`typescript
import { loadReactComponent } from 'htmx-client-routes/react';// Define a route that renders a React component
addRoute('/react-component', () => {
return loadReactComponent(
'my-component', // Component name for identification
React.lazy(() => import("./MyComponent")), // The React component to render
{ prop1: 'value1', prop2: 'value2' } // Props to pass to the component
);
});
`This will render your React component inside an HTMX request, handling all the necessary setup and cleanup.
API
$3
Adds a new route to the client-side router.
-
path: The URL path pattern to match. Can include parameters like {id}, {string}, {integer}, etc.
- handler: Either a string of HTML or a function that returns HTML. The function receives an object with params and elt properties.$3
Gets a route definition that matches the given path.
$3
Extracts parameters from a path based on a route definition.
$3
Cleans up parameters from HTMX request.
$3
Helper function to process HTMX elements after rendering.
$3
Renders a React component for use with HTMX.
-
componentName: A unique name for the component instance
- Component: The React component to render
- componentProps: Optional props to pass to the component
- loader`: Boolean to show/hide a loading spinner (default: true)MIT