1.5.0 • Published 2 years ago

@blakeembrey/react-location v1.5.0

Weekly downloads
36
License
Apache-2.0
Repository
github
Last release
2 years ago

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, Redirect, useRouter, Router } from "@blakeembrey/react-location";

const App = () => {
  // Or `const [url, location] = useRouter()`.

  return (
    <Router>
      {(url, location) => {
        return (
          <div>
            <nav>
              <Link to="/">Home</Link>
              <Link to="/about">About</Link>
            </nav>

            {url.pathname === "/" && <div>Home</div>}
            {url.pathname === "/about-me" && <Redirect to="/about" />}
            {url.pathname === "/about" && <div>About</div>}
          </div>
        );
      }}
    </Route>
  );
};

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

1.5.0

2 years ago

1.4.4

2 years ago

1.4.3

2 years ago

1.4.2

2 years ago

1.4.1

2 years ago

1.4.0

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.2.3

3 years ago

1.2.2

3 years ago

1.2.1

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago