Search code examples
reactjsreduxreact-reduxreact-routerconnected-react-router

connected-react-router app updates url but not components


I've double checked all the tutorials and FAQs but I can't seem to figure out where my problem lies.

Full example here: https://stackblitz.com/edit/react-hmuwhx?embed=1&file=App.js

Some code of interest below. Help appreciated!

export const createRootReducer = history =>
  combineReducers({
    router: connectRouter(history),
    ui: uiReducer,
    user: userReducer
  });

const middlewares = [ReduxThunk];

export const history = createBrowserHistory();

export const store = createStore(
  createRootReducer(history),
  compose(applyMiddleware(...middlewares, routerMiddleware(history)))
);

<Provider store={store}>
  <App history={history} />
</Provider>

export class App extends React.Component {
  render() {
      return (
      <ConnectedRouter history={this.props.history}>
          <div className="full-height">
          <InitializingContainer>
              History length: {this.props.history.length}
              <Switch>
              <Route exact={true} path="/" component={HomePage} />
              <Route path="/test" render={() => <div>Test</div>}/>
              </Switch>
          </InitializingContainer>
          </div>
      </ConnectedRouter>
      );
  }
}

export class HomePage extends React.Component {
  render() {
    return (
      <ul>
        <li>You are here: {this.props.match.path}</li>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/test">Test</Link>
        </li>
      </ul>
    );
  }
}

Solution

  • The problem is that your InitializingContainer is not receiving the Router props and hence not listening to the route history context changes.

    Making use of withRouter with connect like

    export const InitializingContainer = connect(
      mapStateToProps,
      mapDispatchToProps
    )(withRouter(Initializing));
    

    solves the problem.