Meet npm Pro: unlimited public & private packages + package-based permissions.Learn more »

@blakeembrey/react-route

4.1.0 • Public • Published

React Route

NPM version NPM downloads Build status Test coverage

Path-to-RegExp with React Location.

Installation

npm install @blakeembrey/react-route --save

Usage

Use with React Location.

import { Route, Switch, useMatch, usePath } from "@blakeembrey/react-route";

Route

Conditionally renders children when the path matches the active URL.

const App = () => {
  return (
    <Route path="/page/:id">
      {(params, location) => <div>{JSON.stringify(params)}</div>}
    </Route>
  );
}; // `/123` => `<div>["123"]</div>`

Supports path-to-regexp options as props:

  • sensitive When true, the regexp will be case sensitive. (default: false)
  • strict When true, optional trailing delimiters will not match. (default: false)
  • end When true, the regexp will match to the end of the string. (default: true)
  • start When true, the regexp will match to the beginning of the string. (default: true)

Switch

Component for matching and rendering the first <Route /> of children.

const App = () => {
  return (
    <Switch>
      <Route path="/me">{() => <span>Blake</span>}</Route>
      <Route path="/:id">{([id]) => <div>{id}</div>}</Route>
      <Route end={false}>{() => <div>404 Not Found</div>}</Route>
    </Switch>
  );
}; // `/me` => `<span>Blake</span>`

useMatch

Returns the match of the currently active URL.

const App = () => {
  const match = useMatch("/test");
 
  return <div>{JSON.stringify(result)}</div>;
}; // `/test` => `<div>{"params":[],"index":0,"path":"/test"}</div>`

usePath

Creates a path from a path-to-regexp path and params.

const App = () => {
  const path = usePath("/:id", { id: 123 });
 
  return <Link to={path}>User {id}</Link>;
};

TypeScript

This project uses TypeScript and publishes definitions on NPM.

License

Apache 2.0

Install

npm i @blakeembrey/react-route

DownloadsWeekly Downloads

88

Version

4.1.0

License

Apache-2.0

Unpacked Size

111 kB

Total Files

13

Last publish

Collaborators

  • avatar