15

I'm using React-Router 1.0.0-rc3 together with Redux-Router 1.0.0-beta3.

When using React-Router, you can use useBasename with createHistory to set the base URL for an app, so that you can easily write an app that runs inside a subdirectory. Example:

Instead of this:

import { createHistory } from 'history';

let base = "/app_name/"

<Router history={browserHistory}>
  <Route path={base} component={App}></Route>
</Router>

<Link path={base + "some_path"}>some_path</Link>

You can write in this way using useBasename:

import { createHistory, useBasename } from 'history';

const browserHistory = useBasename(createHistory)({
  basename: "/app_name"
});

<Router history={browserHistory}>
  <Route path="/" component={App}></Route>
</Router>

<Link path="/some_path">some_path</Link>

However, in Redux-Router, you need to pass createHistory instead of history to a reducer:

const store = compose(
  applyMiddleware(m1, m2, m3),
  reduxReactRouter({
    routes,
    createHistory
  }),
  devTools()
)(createStore)(reducer);

How can we use useBasename in this case?

1
  • I am not sure what the second example ( "You can write in this way using useBasename") means. It seems to be using the "history" module (not part of React). Also, if you are already using an imported "browserHistory" object from react-router, you cannot overwrite it with a "const browserHistory" definition. And if I replace that with "newBrowserHistory" instead, I get the error "TypeError: _history.useBasename is not a function". So I honestly cannot make heads or tails of the example.
    – Peter
    Sep 14, 2016 at 0:08

4 Answers 4

13

For react-router v2 or v3 and using react-router-redux v4 instead of redux-router, the setup of the history object will look like this:

import { createHistory } from 'history'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'

const browserHistory = useRouterHistory(createHistory)({
  basename: '<yourBaseUrl>'
})
const history = syncHistoryWithStore(browserHistory, store)

The rest of the setup is as usual when there is no extra base URL.

6
  • Works perfectly, recommended if you're using the latest react-router and react-router-redux
    – T .
    Aug 2, 2016 at 9:31
  • 1
    I'm not using react-router-redux (just regular react-router) but the above code worked for me with the omission of the last line.
    – Matt Dell
    Aug 23, 2016 at 13:32
  • I can't get this to work with the latest version of history: createHistory is not a function. If I const createHistory = require('history').createBrowserHistory; then my route does not seem to get matched with a basename: '/'. Any idea?
    – kadrian
    Oct 13, 2016 at 8:22
  • 3
    I just got it to work using the same (old) version of history as [email protected] does: [email protected]. If anyone gets this to work with one of the latest versions, (e.g. [email protected]) please let me know.
    – kadrian
    Oct 13, 2016 at 9:17
  • 2
    @DamianoBarbati You can't downvote this answer just because it does not work for you now. It is a properly written answer to the original question. Please use your vote down privilege maturely.
    – Diego V
    Feb 24, 2017 at 13:58
2

You can create a function that wraps useBasename:

const createHistoryWithBasename = (historyOptions) => {
  return useBasename(createHistory)({
    basename: '/app_name',
    ...historyOptions
  })
}

And pass it to compose:

const store = compose(
  applyMiddleware(m1, m2, m3),
  reduxReactRouter({
    routes,
    createHistory: createHistoryWithBaseName
  }),
  devTools()
)(createStore)(reducer);
1

The API changes very often so this is what worked for me (I'm using the 2.0.3 version of redux-simple-router). I have defined the custom history in a separate file:

import { useRouterHistory } from 'react-router'
import { createHistory, useBasename } from 'history'
import { baseUrl } from '../config'

const browserHistory = useRouterHistory(useBasename(createHistory))({
  basename: "/appgen"
});

Now I need to initialize the store:

import { syncHistory, routeReducer } from 'redux-simple-router'
import browserHistory from '../misc/browserHistory'

const rootReducer = combineReducers({
  // ...other reducers
  routing: routeReducer
});

const reduxRouterMiddleware = syncHistory(browserHistory);

const finalCreateStore = compose(
  // ...other middleware
  applyMiddleware(reduxRouterMiddleware),
)(createStore);


const store = finalCreateStore(rootReducer, initialState);

Eventually, you need to pass the history to the Router.

import browserHistory from './misc/browserHistory'
import routes from '../routes'

export default class Root extends Component {
  static propTypes = {
    history: PropTypes.object.isRequired
  };

  render() {
    return (
      <Router history={browserHistory}>
        {routes}
      </Router>
    )
  }
}

Before I came up with this, I was using a manual solution. I defined my own Link component and my own redux action that were responsible for prepending the base URL. It might be useful for someone.

Updated Link component:

import React, { Component } from 'react'
import { Link as RouterLink } from 'react-router'
import { baseUrl } from '../config'

export default class Link extends Component {
  render() {
    return <RouterLink {...this.props} to={baseUrl + '/' + this.props.to} />
  }
}

Custom action creator:

import { routeActions } from 'redux-simple-router'
import { baseUrl } from '../config'

export function goTo(path) {
  return routeActions.push(baseUrl + '/' + path);
}

Updated root route:

import { baseUrl } from './config'
export default (
  <Route component={App} path={baseUrl}>
    //...nested routes
  </Route>
);

Note that these custom tools only support pushing updated paths, not the location descriptor object.

2
  • Do you use "browserHistory.push('/otherPage')"? if so - did you setup something else to make it work? I loose the basename when i do... Dec 25, 2016 at 17:23
  • 1
    Nope. It's been a while now but I would say that the right thing to do is to dispatch the goTo action rather than using the low-level API manually.
    – tobik
    Dec 25, 2016 at 19:56
-1

A variant of Diego V's answer that worked for me (without knowing what I was doing):

import { createHistory } from 'history'
import { useRouterHistory } from 'react-router'
...

const _browserHistory = useRouterHistory(createHistory)({
  basename: '/yourbase'
})

const store = createStore(_browserHistory, api, window.__data)
const history = syncHistoryWithStore(_browserHistory, store)

I was replacing:

//const _browserHistory = useScroll(() => browserHistory)()

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.