@blakeembrey/react-location
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

React Location

NPM version NPM downloads Build status Test coverage

Light-weight and universal React.js routing.

Installation

npm install @blakeembrey/react-location --save

Usage

React Location exports a React.js Context to control routing. The default router is SimpleLocation, useful for testing or server-side rendering.

import { Link, useURL } from "@blakeembrey/react-location";

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

  return (
    <div>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>

      {url.pathname === "/" && <div>Home</div>}
      {url.pathname === "/about" && <div>About</div>}
    </div>
  );
};

Location Properties:

  • url Get the locations current URL
  • push(location: string) Push the user to a new URL (e.g. <Link /> or dynamic redirects)
  • format(location: string) Format the URL for <Link />
  • onChange(fn: () => void) Notify fn on URL change (returns an unsubscribe function)

Tip: For a simpler routing experience, combine with @blakeembrey/react-route.

import { Route } from "@blakeembrey/react-route";

export default () => (
  <div>
    <Route path="/">{() => <div>Home</div>}</Route>
    <Route path="/page/:id">{([id]) => <Page id={id} />}</Route>
  </div>
);

Hash Location

import { Context, HashLocation } from "@blakeembrey/react-location";

<Context.Provider value={new HashLocation()}>
  <App />
</Context.Provider>;

History Location

import { Context, HistoryLocation } from "@blakeembrey/react-location";

<Context.Provider value={new HistoryLocation()}>
  <App />
</Context.Provider>;

Simple Location

Useful for testing React.js applications or server-side rendering.

import { Context, SimpleLocation } from '@blakeembrey/react-location'

// E.g. `req.url` from a node.js HTTP server.
const location = new SimpleLocation(new URL(`http://example.com${req.url}`))

<Context.Provider value={location}>
  <App />
</Context.Provider>

TypeScript

This project uses TypeScript and publishes definitions on NPM.

License

Apache 2.0

Package Sidebar

Install

npm i @blakeembrey/react-location

Weekly Downloads

3

Version

2.0.1

License

Apache-2.0

Unpacked Size

19.2 kB

Total Files

6

Last publish

Collaborators

  • blakeembrey