When using mobx-react's observer the application of an active class on react-router's NavLink component is broken.
Setup that produces problem:
using create react 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 display of the problem. My use case involves actually using a mobx store to create the NavLink's and also using decorators. Looking for why the observer wrapper stops react-router-dom from applying the active class.
I just need to stack my class wrappers/decorators. This example was using the base createReactApp so there are no decorators, but the actual use case I had was using typescript fork of createReactApp and did support decorators.
My problem was solved by stacking the decorators on classes so that the context from react router and mobx was passed down.
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{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With