rhums
v3.0.0
Published
React Hook for URL Matching and Subscription
Readme
rhums
React Hook for URL Matching and Subscription
rhums is a dead simple typesafe router for React that's build on top of the URL web API.
import { useUrl, route } from "rhums";
const App = () => {
const url = useUrl();
return route(url.pathname, {
"/": () => <h1>{`Home`}</h1>,
"/users": () => <h1>{`Users`}</h1>,
"/users/:userId/*": ({ userId, rest }) => (
<>
<h1>{`User ${userId}`}</h1>
<UserDetails path={rest} />
</>
),
_: () => <h1>Not found</h1>,
});
};Installation
$ yarn add rhumsAPI
useUrl()
Hook to get the current URL:
const url = useUrl();The returned value is a URL
push(to)
Pushes the page URL
push("/users/bloodyowl");replace(to)
Replaces the page URL
replace("/users/bloodyowl");getUrl()
Returns the current URL
const url = getUrl();watchUrl()
Returns the current URL
const unwatchUrl = watchUrl((url) => {
console.log(url);
});
// ...
unwatchUrl();useNavigationBlocker(shouldBlock, message)
Blocks page navigation if shouldBlock is true.
useNavigationBlocker(
formStatus === "editing",
"Are you sure you want to leave this page?",
);useIsActivePattern(pattern)
Returns whether the provided path is active
const isActive = useIsActivePath("/foo/:userId/bar");route(path, config)
Matches the pathname to the config
- Route params like
:paramNameare selected. - Rest params like
*are selected asrest.
route(url.pathname, {
"/": () => <h1>{`Home`}</h1>,
"/users": () => <h1>{`Users`}</h1>,
"/users/:userId/*": ({ userId, rest }) => (
<>
<h1>{`User ${userId}`}</h1>
<UserDetails path={rest} />
</>
),
_: () => <h1>Not found</h1>,
});route(pathname, pattern)
Checks if a the provided pathname matches a given URL pattern
- Route params like
:paramNameare selected. - Rest params like
*are selected asrest.
route(url.pathname, {
"/": () => <h1>{`Home`}</h1>,
"/users": () => <h1>{`Users`}</h1>,
"/users/:userId/*": ({ userId, rest }) => (
<>
<h1>{`User ${userId}`}</h1>
<UserDetails path={rest} />
</>
),
_: () => <h1>Not found</h1>,
});matchPattern(pathname, pattern)
Matches the pathname agaisnt the pattern. Returns the params in case of match, returns undefined otherwise.
matchPattern(url.pathname, "/users/:userId/*"); // {userId: "foo", rest: "/bar"}
matchPattern(url.pathname, "/profiles/:profileId/*"); // undefinedmatchesPattern(pathname, pattern)
Checks if the pathname matches the pattern.
matchesPattern(url.pathname, "/users/:userId/*"); // true
matchesPattern(url.pathname, "/profiles/:profileId/*"); // falseInspirations
- Rescript React Router for the whole API
- Chicane for the TypeScript wizardy logic
