# mobx-react-router

> Keep your MobX state in sync with react-router

Latest version **6.1.0** (published 2024-12-02) · MIT license · 0 weekly downloads

## Install

```sh
npm install mobx-react-router
pnpm add mobx-react-router
yarn add mobx-react-router
bun add mobx-react-router
```

## Health

**Score 55/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high maintenance score; high quality score.

Warnings: low downloads.

Negative: stale.

## Facts

| | |
|---|---|
| Version | 6.1.0 |
| Published | 2024-12-02 |
| First published | 2016-10-05 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 20.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 437 |
| Author | Ali Sheehan-Dare - @im_alisd |
| Maintainers | alisd23, gcattan |
| Keywords | react, react-router, routing, router, mobx, state, store |

## Links

- npm: https://www.npmjs.com/package/mobx-react-router
- Repository: https://github.com/IBM/mobx-react-router
- Homepage: https://github.com/IBM/mobx-react-router#readme
- Issues: https://github.com/IBM/mobx-react-router/issues
- npm.io page: https://npm.io/package/mobx-react-router

## Dependencies (1)

- [@types/node](https://npm.io/package/@types/node.md) ^22.7.4

## Alternatives

- [express-promise-router](https://npm.io/package/express-promise-router.md) — 736.1K weekly downloads
- [next-usequerystate](https://npm.io/package/next-usequerystate.md) — 29.8K weekly downloads
- [@bitkyc08/opencodex](https://npm.io/package/@bitkyc08/opencodex.md) — 4.6K weekly downloads
- [lynkr](https://npm.io/package/lynkr.md) — 575 weekly downloads
- [baremetal.js](https://npm.io/package/baremetal.js.md) — 42 weekly downloads

## Recent versions

- 6.1.0 (latest) — 2024-12-02
- 6.1.0-alpha — 2024-10-28
- 6.0.1 — 2024-05-01
- 6.0.0 — 2024-03-01
- 6.0.0-alpha — 2024-02-03
- 5.0.3 — 2023-11-09
- 5.0.2 — 2023-07-12
- 5.0.1 — 2023-05-26
- 5.0.0 — 2023-01-05
- 4.1.0 — 2019-12-10
- 4.0.7 — 2019-03-25
- 4.0.6 — 2019-03-22
- 4.0.5 — 2018-09-08
- 4.0.4 — 2018-05-23
- 4.0.3 — 2018-04-29
- … 11 more at https://npm.io/package/mobx-react-router/versions

## 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](https://github.com/reactjs/react-router-redux/tree/master).

- [Installation](#installation)
- [Usage](#usage)
- [API](#api)
  - [RouterStore](#routerstore)
  - [syncHistoryWithStore](#synchistorywithstorehistory-store)


This branch (master) is for use with **react-router v6**.
Please, check the branch [v5](https://github.com/IBM/mobx-react-router/tree/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:

```bash
npm install --save mobx mobx-react react-router
```

## Usage

`index.js`
```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`
```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](https://stackblitz.com/edit/github-bje76z-uyn64v?file=README.md) with Vite.js.

### 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

```js
const store = new RouterStore();
```

A **router store** instance has the following properties:

- `location` (*observable*) - history [location object](https://github.com/mjackson/history#listening)
- `history` - raw [history API](https://github.com/mjackson/history#properties) object

And the following [history methods](https://github.com/mjackson/history#navigation):

- **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
```js
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

```js
history.unsubscribe();
// Store no longer updates
```

---
_Source: https://npm.io/package/mobx-react-router · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
