1

I want to navigate to path /hello and try the following:

import { browserHistory } from 'react-router'
browserHistory.push('/hello')

But it only changes the browser's URL to /hello without actually navigating to that page. Inside of a component, this method works:

this.props.history.push('/hello')

This is how I set up my router:

// Configure history for react-router
const browserHistory = useRouterHistory(createBrowserHistory)({
  basename: __BASENAME__
})

// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the key "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.__INITIAL_STATE__
const store = configureStore(initialState, browserHistory)
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: (state) => state.router
})

// Now that we have the Redux store, we can create our routes. We provide
// the store to the route definitions so that routes have access to it for
// hooks such as `onEnter`.
const routes = makeRoutes(store)

// Now that redux and react-router have been configured, we can render the
// React application to the DOM!
ReactDOM.render(
  <Root history={history} routes={routes} store={store} />,
  document.getElementById('root')
)

References:

  1. https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#programmatic-navigation
  2. https://github.com/reactjs/react-router/issues/1081

1 Answer 1

2

When I setup the browserHistory, I store it inside a global namespace:

const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: (state) => state.router
})
window.routerHistory = history

Then I can navigate outside of a component like below:

window.routerHistory.push('/')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.