Skip to content

Adding routing to a plugin

Louise Davies edited this page Feb 18, 2020 · 4 revisions

Adding routing to an app is relatively straight forward, it mainly involves using react-router to change pages and change what components get mounted. If the plugin has Redux as well then you can also hook in the route history into the redux state as well as allowing components to fire actions to change the route.

To add routing, first install the required packages:

yarn add react-router react-router-dom connected-react-router

Update the top level reducer to accept a history argument and add a router part to the state (n.b. it must be called router for the library to hook into the state)

import { connectRouter } from 'connected-react-router';
import { History } from 'history';
{{other imports}}
...

const AppReducer = (history: History): Reducer =>
  combineReducers({
    router: connectRouter(history),
    {{other parts of the state}}
  });

Finally update index.tsx with a browser history, router middleware, pass the history into the reducer and added a connected router component:

import { createBrowserHistory } from 'history';
import { routerMiddleware, ConnectedRouter } from 'connected-react-router';
import { Route, Switch } from 'react-router'; // react-router v4
...

const history = createBrowserHistory();
const middleware = [{{other middleware}}, routerMiddleware(history)];
...

const store = createStore(
  AppReducer(history),
  composeEnhancers(applyMiddleware(...middleware))
);
...

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route exact path="/" render={() => <App />} />
        {{other routes}}
      </Switch>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);
Clone this wiki locally