Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router props `location` / `match` not updating with `ConnectedRouter`

I've got my app setup as in the docs:

Step 1

...
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { connectRouter, routerMiddleware } from 'connected-react-router'
...
const history = createBrowserHistory()

const store = createStore(
  connectRouter(history)(rootReducer), // new root reducer with router state
  initialState,
  compose(
    applyMiddleware(
      routerMiddleware(history), // for dispatching history actions
      // ... other middlewares ...
    ),
  ),
)

Step 2

...
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router' // react-router v4
import { ConnectedRouter } from 'connected-react-router'
...
ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
      <div> { /* your usual react-router v4 routing */ }
        <Switch>
          <Route exact path="/" render={() => (<div>Match</div>)} />
          <Route render={() => (<div>Miss</div>)} />
        </Switch>
      </div>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('react-root')
)

I click on a Link or even dispatch(push('/new-url/withparam'))

However the props for match location are remaining the previous values or whatever the first page was.

What is happening?

like image 260
ilovett Avatar asked Aug 17 '18 22:08

ilovett


1 Answers

This one has bitten me many times.

Your Switch and Route etc. MUST NOT BE INSIDE A CONNECTED COMPONENT!

If the component is connected, the props for match, location, etc. don't seem to get updated and propagate down to your routes.

This means don't connect your top level App or Root, or any other nested containers between the ConnectedRouter and Route

--

Update:

You may just need to wrap your component with

<Route render={ (routerProps) => <YourConnectedComponent { ...routerProps } />
like image 132
ilovett Avatar answered Jan 03 '23 10:01

ilovett