Search code examples
reactjsreduxreact-routerreact-reduxreact-router-dom

Usign react-router-dom, how can I access browserHistory object from outside a React component?


With the previous react-router I was able to do this:

import {browserHistory} from 'react-router';

from my actionCreators file and I could do something like this:

...some async action completed (for example, user logged in successfully)..
browserHistory.push('/dashboard');

But with the new react-router-dom (v4) it seems like I can no longer import browserHistory just like that and that the only way to access the history object is from a React components props

this.props.history

What would be a way to redirect my user to a new page after an async redux action has completed using react-router-dom?


Solution

  • withRouter is what you're looking for.

    "You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component."

    import React, { PropTypes } from 'react'
    import { withRouter } from 'react-router'
    
    // A simple component that shows the pathname of the current location
    class ShowTheLocation extends React.Component {
      static propTypes = {
        match: PropTypes.object.isRequired,
        location: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired
      }
    
      render() {
        const { match, location, history } = this.props
    
        return (
          <div>You are now at {location.pathname}</div>
        )
      }
    }
    
    // Create a new component that is "connected" (to borrow redux
    // terminology) to the router.
    const ShowTheLocationWithRouter = withRouter(ShowTheLocation)