@blakeembrey/react-location
v2.0.1
Published
Light-weight and universal React.js routing
Downloads
60
Maintainers
Readme
React Location
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 URLpush(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)
Notifyfn
on URL change (returns anunsubscribe
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