Search code examples
reactjsreact-routerredux-router

React router not routing when wrapped


If you could point the error it will be grateful, I'm frazzled. I'm using react router as such:

<Router history={history}>
    <div>
        <Route exact path="/" component={SplashScreen} />
         <Route path="/login" component={LoginComponent} />
      </div>
</Router>

This works perfectly fine. The moment however I wrap another component around the div, in this case a StartupLogic component, routing stops working Specifically I'm using:

dispatch(push("/login"));

When StartupLogic is not wrapped around the div this works fine meaning the url bar changes to localhost:3000/login and the LoginComponent is mounted.

When the StartupLogic component IS mounted around the div, the url bar changes to localhost:3000/login but the LoginComponent doesnt render, I'm stuck there looking at the SplashScreen.

The StartupLogic component:

class AppDelegate extends Component {

  componentDidMount(){
    this.props.getX().then(allCountries => {
      this.props.getY().then(res => {

        setTimeout(() => {

          console.log(this);
          debugger;
          this.forceUpdate();
        },5000)

      });
    });
  }

  render() {
    return (
      <div>
        {this.props.children}
      </div>
    );
  }
}

Solution

  • Instead of Wrapping the Routes within a component like

    <Router history={history}>
        <StartupLogic >
          <div>
            <Route exact path="/" component={SplashScreen} />
             <Route path="/login" component={LoginComponent} />
          </div>
        <StartupLogic >
    </Router>
    

    you should move the Routes within the component directly and get get the Route params using withRouter in the WrappedRoute like

    const StartupLogic = () => {
       return (
          <div>
            <Route exact path="/" component={SplashScreen} />
             <Route path="/login" component={LoginComponent} />
          </div>
       )
    }
    
    export default withRouter(StartupLogic);
    

    and use it like

    <Router history={history}>
        <StartupLogic />
    </Router>