Giter Site home page Giter Site logo

cap32 / react-router-mobx Goto Github PK

View Code? Open in Web Editor NEW
14.0 4.0 0.0 123 KB

๐Ÿ“ก When React Router meets MobX: observable router and location

License: MIT License

JavaScript 100.00%
react react-router router mobx observable query querystring location

react-router-mobx's Introduction

react-router-mobx

Build Status Coverage Status npm version License

When React Router meets MobX: observable router and location.

Table of Contents

Features

  • location is observable
  • Built-in query observable object to location
  • Super easy to push/update new URL, pathname, hash, search or query

WTF

If you wanna push url from http://aweso.me/search?q=hello&page=4 to http://aweso.me/search?q=hello&page=5, you may need:

Before
import React, { Component } from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router-dom";
import { observer } from "mobx-react";
import qs from "qs";
import myStore from "./stores/myStore";

@withRouter
@observer
export default class MyApp extends Component {
  static propTypes = {
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  goToNextPage = ev => {
    ev.preventDefault();
    const { location, history } = this.props;
    const query = qs.parse(location.search ? location.search.slice(1) : "");
    history.push({
      ...location,
      search:
        "?" +
        qs.stringify({
          ...query,
          page: 1 + query.page
        })
    });
  };

  render() {
    const { location } = this.props;
    const { page } = qs.parse(location.search ? location.search.slice(1) : "");
    return (
      <div>
        <div>{myStore.someContent}</div>
        <p>Page: {page || 1}</p>
        <button onClick={this.goToNextPage}>Next</button>
      </div>
    );
  }
}
After
import React, { Component } from "react";
import PropTypes from "prop-types";
import { observer } from "mobx-react";
import myStore from "./stores/myStore";
import routerStore from "./stores/routerStore";

@observer
export default class MyApp extends Component {
  goToNextPage = ev => {
    ev.preventDefault();
    const { location } = routerStore;
    location.query = {
      ...location.query,
      page: 1 + location.query.page
    };
  };

  render() {
    const { page } = routerStore.location.query;
    return (
      <div>
        <div>{myStore.someContent}</div>
        <p>Page: {page || 1}</p>
        <button onClick={this.goToNextPage}>Next</button>
      </div>
    );
  }
}

Installation

yarn add react-router-mobx

You should install all the peer dependencies if you haven't installed them:

yarn add react mobx mobx-react react-router-dom

If you are using React Native, please install react-router-native instead of react-router-dom.

Usage

  1. Use react-router-mobx Router instead of react-router Router
  2. Pass a RouterStore instance and react-router Router component to Router component:
import React, { Component } from "react";
import { Router, RouterStore } from "react-router-mobx";
import { BrowserRouter, Route } from "react-router-dom";

const routerStore = new RouterStore();

export default class App extends Component {
  render() {
    return (
      <Router component={BrowserRouter} routerStore={routerStore}>
        <Route {...someRouteConfigs} />
      </Router>
    );
  }
}

API Reference

RouterStore

The MobX store class that contains some router properties and methods.

RouterStore#location

A little bits like react-router location object which contains key, pathname, search, hash, state. But there are several differences:

  • Prividing query object, just like react-router v3 or below
  • All properties are observable and mutable
  • Could push URL by passing new location or properties, just like window.location
    • Push a new URL: routerStore.location = '/foo?say=hello'
    • Push a new pathname, i.e. from /foo?say=hello to /bar?say=hello: routerStore.location.pathname = '/bar'
    • Push a new search, i.e. from /foo?say=hello to /foo?say=world: routerStore.location.query = { say: 'world' } or routerStore.location.search = '?say=world'
RouterStore#history

Just like react-router history object, except for history.listen:

history.listen((location, prevLocation, action) => {
  console.log(
    `The current URL is ${location.pathname}${location.search}${location.hash}`
  );
  console.log(
    `The previous URL is ${prevLocation.pathname}${prevLocation.search}${
      prevLocation.hash
    }`
  );
});
RouterStore#push(loc, state)

Like react-router history.push(loc, state), but the loc param supports to be an object that contains a query object.

RouterStore#replace(loc, state)

Like react-router history.replace(loc, state), but the loc param supports to be an object that contains a query object.

Router

The low-level api router component instead of react-router Router component.

Props
  • routerStore (RouterStore): Defining a RouterStore instance to store or update location state
  • component (ReactComponent): Defining the react router component, e.g. BrowserRouter, MemoryRouter, NativeRouter, etc. Defaults to react-router Router component
  • history (Object): You can also define a custom history object, just like react-router Router component
  • All properties in react-router Router are supported

setQueryString(queryString)

Setting a custom queryString library.

Arguments
  1. queryString (Object): Custom queryString library, which should contain parse(object) and stringify(object) methods
Example
import { setQueryString } from "react-router-mobx";
import { parse, stringify } from "qs";
setQueryString({ parse, stringify });

match

Please note that routerStore doesn't provide a match prop, if you need match, you may also use withRouter or <Route> from react-router. Checkout match for detail.

Versioning

This library follows Semantic Versioning.

This library is considered to be General Availability (GA). This means it is stable; the code surface will not change in backwards-incompatible ways unless absolutely necessary (e.g. because of critical security issues) or with an extensive deprecation period. Issues and requests against GA libraries are addressed with the highest priority.

License

MIT

react-router-mobx's People

Contributors

cap32 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-router-mobx's Issues

[email protected]" has incorrect peer dependency "mobx@^3.0.0".

Does it work?

		"mobx": "^4.2.0",
yarn add react-router-mobx
yarn add v1.6.0
[1/4] ๐Ÿ”  Resolving packages...
[2/4] ๐Ÿšš  Fetching packages...
[3/4] ๐Ÿ”—  Linking dependencies...
warning " > [email protected]" has incorrect peer dependency "mobx@^3.0.0".
[4/4] ๐Ÿ“ƒ  Building fresh packages...
success Saved lockfile.
success Saved 2 new dependencies.
info Direct dependencies
โ””โ”€ [email protected]
info All dependencies
โ”œโ”€ [email protected]
โ””โ”€ [email protected]
โœจ  Done in 8.06s.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.