npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ibm/mobx-react-router

v6.0.0

Published

Keep your MobX state in sync with react-router

Downloads

13,283

Readme

/!\ The NPM location of this repository has changed /!\

Use @ibm/mobx-react-router

mobx-react-router

Keep your MobX state in sync with react-router via a RouterStore.

Router location state is observable, so any references to it in MobX components will cause the component to re-render when the location changes.

Very much inspired by (and copied from) react-router-redux.

This branch (master) is for use with react-router v6. Please, check the branch v5 for react-router v5.

Installation

npm install --save @ibm/mobx-react-router

/!\ npm install --save mobx-react-router is now deprecated, use npm install --save @ibm/mobx-react-router

And if you haven't installed all the peer dependencies, you should probably do that now:

npm install --save mobx mobx-react react-router

Although, mobx v6 deprecated decorators, this library still requires to enable them. Below is an example of configuration using vite.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  target: 'es2015',
  plugins: [
    react({
      babel: {
        plugins: [
          ['@babel/plugin-proposal-decorators', { legacy: true }],
        ],
      },
    }),
  ],
});

For more details, please consult the documentation of mobx v6 on decorators.

Usage

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createBrowserHistory } from 'history';
import { Provider } from 'mobx-react';
import { RouterStore, syncHistoryWithStore } from '@ibm/mobx-react-router';
import { Router } from 'react-router';
import App from './App';

const browserHistory = createBrowserHistory();
const routingStore = new RouterStore();

const stores = {
  // Key can be whatever you want
  routing: routingStore,
  // ...other stores
};

const history = syncHistoryWithStore(browserHistory, routingStore);

ReactDOM.render(
  <Provider {...stores}>
    <Router location={routingStore.location} navigator={history}>
      <App />
    </Router>
  </Provider>,
  document.getElementById('root')
);

App.js

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';

@inject('routing')
@observer
export default class App extends Component {
  render() {
    const { location, push, back } = this.props.routing;

    return (
      <div>
        <span>Current pathname: {location.pathname}</span>
        <button onClick={() => push('/test')}>Change url</button>
        <button onClick={() => back()}>Go Back</button>
      </div>
    );
  }
}

Check our live example.

HashRouter

You can replace history/createBrowserHistory with history/createHashHistory in the example above to use hash routes instead of HTML5 routing.

Troubleshooting

Routes not updating correctly when URL changes

There is a known issue with React Router 4 and MobX (and Redux) where "blocker" components like those created by @observer (and @connect in Redux) block react router updates from propagating down the component tree.

To fix problems like this, try wrapping components which are being "blocked" with React Router's withRouter higher order component should help, depending on the case.

API

RouterStore

const store = new RouterStore();

A router store instance has the following properties:

And the following history methods:

  • push(path)
  • replace(path)
  • go(n)
  • back()
  • forward()

syncHistoryWithStore(history, store)

  • history - A variant of a history object, usually browserHistory
  • store - An instance of RouterStore

returns an enhanced history object with the following additional methods:

  • subscribe(listener)
    Subscribes to any changes in the store's location observable
    Returns an unsubscribe function which destroys the listener
const unsubscribeFromStore = history.subscribe((location, action) => console.log(location.pathname));

history.push('/test1');
unsubscribeFromStore();
history.push('/test2');

// Logs
// 'test1'
  • unsubscribe()
    Un-syncs the store from the history. The store will no longer update when the history changes
history.unsubscribe();
// Store no longer updates