Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
Alejandro Figueroa Avatar asked Apr 06 '17 02:04

Alejandro Figueroa


People also ask

How do you use history outside react component?

We would obviously want some additional logic in there, but the point is that we can access the history object through props , even though no props were passed to Login , and use history. push to push a new entry onto the history stack.

How do you use .push history in react?

Using history.push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.


1 Answers

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)
like image 80
Tyler McGinnis Avatar answered Sep 22 '22 22:09

Tyler McGinnis