Why react router switch doesn't work when window location changed?

Viewed 337

React router switch works fine when I using Redirects, Navlinks or other library staff.

The problem is in function loadOrderPage. When its fired, window location changes OK but page not re-render accordingly to react-router switch rules, so component for '/order' doesn't render after this function complete.

here is my simple react class

Live working example here: https://codesandbox.io/s/delicate-wildflower-sdvd4?file=/src/App.js

import React from "react";
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Switch,
} from "react-router-dom";
import Startpage from "./components/startpage";
import Orderpage from "./components/orderpage";
import { withRouter } from "react-router";

class App extends React.Component {

.......

  loadOrderPage = () => {
    this.props.history.push("/order");
  };

  render() {

    return (
      <Router>
        <Switch>
          <Route path="/order">
            <Orderpage />
          </Route>
          <Route path="/">
            <Startpage/>
          </Route>
        </Switch>
      </Router>
    );
  }
}

export default withRouter(App);

Whats wrong? I want to able change window location in functions and waiting that react router would render correct components under switch rules. May be its more suitable methods are available?

1 Answers

You cannot have two defined, both in your index.js and in your App.js. Remove the <Router></Router> from your App.js.

Make sure to add exact to your <Route />.

<Route exact path="/order">
  <Orderpage />
</Route>
<Route exact path="/">
   <Startpage/>
</Route>
Related