Light-weight and universal React.js routing.
npm install @blakeembrey/react-location --save
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>
);
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>
This project uses TypeScript and publishes definitions on NPM.
Apache 2.0