Skip to content

blakeembrey/react-location

Repository files navigation

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>
);
import { Context, HashLocation } from "@blakeembrey/react-location";

<Context.Provider value={new HashLocation()}>
  <App />
</Context.Provider>;
import { Context, HistoryLocation } from "@blakeembrey/react-location";

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

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