1

Goal

I'm trying to extract the <Switch> with its <Route>'s out to a different module.

Problem

The url is being changed to the new path, but the content doesn't (only when I refresh it changes).

I'm trying to understand what am I missing.

EDITED: live example: https://stackblitz.com/edit/separated-switch-module

working example:

<BrowserRouter>
  <div>
    <Link to="/"> Home </Link>
    <Link to="contacts"> Contacts </Link>

    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/contacts" component={Contacts} />
    </Switch>
  </div>
</BrowserRouter>

failing exmaple:

<BrowserRouter>
  <div>
    <Link to="/"> Home </Link>
    <Link to="contacts"> Contacts </Link>
    <SwitchedRoutes/>
  </div>
</BrowserRouter>

EDITED:

SwitchedRoutes:

import React from "react";
import { observer, inject } from "mobx-react";
import { Switch, Route } from "react-router-dom";

@inject('pageStore')
@observer
export default class extends React.Component {
    render(){   
        const {
            home,
            contacts
        } = this.props.pageStore.pages;

        return (
            <Switch>
                <Route exact path={home.path} render={()=> <Home />} />
                <Route path={contacts.path} render={()=> <Contacts/>} />
            </Switch>
        )
    }
}
ueeieiie
  • 1,014
  • 10
  • 33

1 Answers1

3

Since react-router v4 changed an API a bit you need to give to the all underlying components such as Switch, Link and etc a router context. (Something like subscriber to the routing stuff), as soon as you disconnects the module to the separate file it loses the context.

just add this to the SwitchedRoutes.js

import React from 'react';
import { withRouter } from 'react-router'
import {Switch, Route} from 'react-router-dom';
import {inject, observer} from 'mobx-react';

const Home = () => <h1>Home</h1>;
const Contacts = () => <h1>Contents</h1>;


const switchedRouter = inject('store')(observer(props => {
  const {home, contacts} = props.store.routes;

  return(
    <Switch>
      <Route exact path={home.path} component={Home}/>
      <Route path={contacts.path} component={Contacts}/>
    </Switch>
  );
}));

export default withRouter(switchedRouter)

we simply wrapped the component with withRouter HoC which provides us a correct react-router context.

https://separated-switch-module-j92psu.stackblitz.io

Milos Mosovsky
  • 2,447
  • 1
  • 12
  • 16
  • Dang, got there before me. Fix [here](https://stackblitz.com/edit/separated-switch-module-shna4y?file=SwitchedRoutes.js) anyway. – Colin Ricardo Apr 25 '18 at 17:01