0
votes

So basically, when I try to change the route from one of the routes, I am calling this.props.history.push('/newPath'). Browser url changes, however new path does not get matched (I assume), because render function of the same components gets called and nothing changes..

index.tsx with router:

import * as React from 'react';
import * as ReactDOM from "react-dom";
import { Router, Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import history from '../services/history.js';

import rootReducer from '../reducers';

import Browse from './browse';
import ShopItem from './shop-item';

import * as Styles from './index.scss';

const BrowserContainer = () => {
  const initialState: any = {
    items: window.preloadedData.items || []
  };
  const middlewares = [thunk];
  const store = createStore(rootReducer, initialState, 
applyMiddleware(...middlewares));

  return (
    <Provider store={ store }>
      <Router history={ history }>
        <div className={ Styles['container'] }>
          <Route exact path="/item/:id" component={ ShopItem } />
          <Route exact path="/home" component={ Browse } />
        </div>
      </Router>
    </Provider>
  );
};

ReactDOM.render(
  <BrowserContainer />,
  document.getElementById("root")
);

Component I am trying to navigate from is connected to redux store using connect function. I have tried wrapping it into withRouter() HOC and remove connect at all, no success. Function I am calling to change route:

getItemAndNavigate(id: string) {
  this.props.history.push(`/item/${id}`);
}

Versions: "history": "^4.7.2", "react-router-dom": "^4.2.2"

1

1 Answers

0
votes

You need to use this.context.router.history.push. Check your debugger in Chrome. They upgraded to version 4. It is a total rewrite of previous versions. Let me know if you need more help. Set breakpoints to see what is being returned. In addition,<Router> is now <BrowserRouter>. You don't need history anymore.

EDIT: I made a mistake and use this.props.router.history, it should be using context and use BrowserContainer.contextTypes = {router: PropTypes.object};