项目作者: blakeembrey

项目描述 :
Light-weight and universal react routing
高级语言: TypeScript
项目地址: git://github.com/blakeembrey/react-location.git
创建时间: 2018-11-25T01:20:16Z
项目社区:https://github.com/blakeembrey/react-location

开源协议:Other

下载


React Location

@blakeembrey/react-location"">NPM version
@blakeembrey/react-location"">NPM downloads
Build status
Test coverage

Light-weight and universal React.js routing.

Installation

  1. 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.

  1. import { Link, useURL } from "@blakeembrey/react-location";
  2. const App = () => {
  3. const url = useURL();
  4. return (
  5. <div>
  6. <nav>
  7. <Link to="/">Home</Link>
  8. <Link to="/about">About</Link>
  9. </nav>
  10. {url.pathname === "/" && <div>Home</div>}
  11. {url.pathname === "/about" && <div>About</div>}
  12. </div>
  13. );
  14. };

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.

  1. import { Route } from "@blakeembrey/react-route";
  2. export default () => (
  3. <div>
  4. <Route path="/">{() => <div>Home</div>}</Route>
  5. <Route path="/page/:id">{([id]) => <Page id={id} ></Page>}</Route>
  6. </div>
  7. );

Hash Location

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

History Location

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

Simple Location

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

  1. import { Context, SimpleLocation } from '@blakeembrey/react-location'
  2. // E.g. `req.url` from a node.js HTTP server.
  3. const location = new SimpleLocation(new URL(`http://example.com${req.url}`))
  4. <Context.Provider value={location}>
  5. <App ></App>
  6. </Context.Provider>

TypeScript

This project uses TypeScript and publishes definitions on NPM.

License

Apache 2.0