Skip to content

A simple Router for your TypeScript React applications

License

Notifications You must be signed in to change notification settings

bloodyowl/use-url

Repository files navigation

bloody-use-url

A simple router for React applications

import { useUrl, route } from "bloody-use-url";
import { match } from "ts-pattern";

const App = () => {
  const url = useUrl();

  return match(url.path)
    .with(route("/"), () => <h1>{`Home`}</h1>)
    .with(route("/users"), () => <h1>{`Users`}</h1>)
    .with(route("/users/:userId/*"), ({ userId, rest }) => (
      <>
        <h1>{`User ${userId}`}</h1>
        <UserDetails path={rest} />
      </>
    ))
    .otherwise(() => <h1>Not found</h1>);
};

Installation

$ yarn add bloody-use-url ts-pattern

API

useUrl()

Hook to get the current URL:

const url = useUrl();

The returned value has the following type:

type Url = {
  path: string[];
  search: URLSearchParams;
  hash: string;
  pathname: string;
};

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?"
);

useIsActivePath(path)

Returns whether the provided path is active

const isActive = useIsActivePath("/foo/bar");

route(path)

Generates a pattern to be consumed by ts-pattern:

  • Route params like :paramName are selected.
  • Rest params like * are selected as rest.
return (
  match(url.path)
    .with(route("/"), () => <h1>{`Home`}</h1>)
    .with(route("/users"), () => <h1>{`Users`}</h1>)
    // `userId` & `rest` are correctly typed
    .with(route("/users/:userId/*"), ({ userId, rest }) => (
      <>
        <h1>{`User ${userId}`}</h1>
        <UserDetails path={rest} />
      </>
    ))
    .otherwise(() => <h1>Not found</h1>);
);

Inspirations

About

A simple Router for your TypeScript React applications

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published