Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 baseName and custom history

I would like to assign a basename to my routes, which I can with BrowserRouter.

I would also however like to specify a custom history so I can programatically navigate my users. Which I can do, with Router.

I can't however, do both. Is it possible to extend one of the routers to support this or wrap function round it to add this?

My current setup is this -

import React from 'react';
import { Router, Switch, Route, Redirect } from 'react-router-dom';

import createHistory from './history';

import Navigation from './components/navigation/Navigation';

import PrivateRoute from './components/private-route/PrivateRoute';

import Home from './containers/home/Home';
import PageTwo from './components/pageTwo/PageTwo';
import Callback from './components/callback/Callback';
import Login from './components/login/Login';

export default () => (
  <Router history={createHistory}>
    <div>
      <Navigation />
      <Switch>
        <Route path="/callback" component={Callback} />
        <Route path="/login" component={Login} />
        <PrivateRoute path="/" exact component={Home} />
        <PrivateRoute path="/page-two" component={PageTwo} />
        <Redirect to="/" />
      </Switch>
    </div>
  </Router>
);

However I'd love to achieve something such as -

<Router history={createHistory} basename="foo">
like image 514
Harry Blue Avatar asked Nov 30 '17 18:11

Harry Blue


1 Answers

You can:

<BrowserRouter basename="/your/app">
  <App/>
</BrowserRouter>

Or to directly configure the history object:

import { Router } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory({ basename: '/your/app' });

<Router history={history}>
  <App />
</Router>
like image 74
Robert Farley Avatar answered Sep 20 '22 14:09

Robert Farley