Why is the mobx browser responsive to the nav-on-router-dom navlink active activity class?

When using mobx-react

observer

an active class application on a component is react-router

NavLink

broken.

The setting that poses the problem:

using create response app

package.json

{
  "name": "routertest",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "mobx": "^3.1.9",
    "mobx-react": "^4.1.8",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^4.1.1"
  },
  "devDependencies": {
    "react-scripts": "0.9.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

      

App.js

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom'
import Nav from './Nav';
import './App.css';

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

const About = () => (
  <div>
    <h2>About</h2>
  </div>
)
const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
  </div>
)



class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div className="App">
          <Nav />
          <hr />
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/topics" component={Topics} />
        </div>
      </BrowserRouter >
    );
  }
}

export default App;

      

Nav.js

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import { observer } from 'mobx-react';

const Nav = observer (class Nav extends Component {
    render() {
        return (
            <ul>
                <li><NavLink exact to="/" activeClassName="active">Home</NavLink></li>
                <li><NavLink to="/about" activeClassName="active">About</NavLink></li>
                <li><NavLink to="/topics" activeClassName="active">Topics</NavLink></li>
            </ul>
        );
    }
})

export default Nav;

      

This is a simplified representation of the problem. In my use case it is actually used mobx store

for creation NavLink

as well as using decorators. Look for why the observer shell stops react-router-dom

the active class from being applied.

+3


source to share


1 answer


I just need to stack the class wrappers / decorators. This example used base createReactApp so there are no decorators, but the actual use case I used was using typescript fork createReactApp and supported decorators.

My problem was solved by stacking decorators on classes so that context

from react router and mobx was passed.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md



Example:

@withRouter
@inject('store')
@observer
export class MyComponent extends React.Component{
...
}

      

+4


source







All Articles