score:0

Starting from React Router v4, browserHistory is no longer exported from react-router.

You have two possibilities.

1) If your component is rendered via a route (is the component prop of a <Route> component, then you automatically get a few objects as props:

  • history
  • match
  • location

You can then use this.props.history.push("/some_location") in the context of the component

2) If your component is not related to a specific route, you can get the same props by using the withRouter high order component, which is part of react-router

import { withRouter } from "react-router-dom";

const Component = ( { history, location, match } ) => (
// your component code
);

export default withRouter(Component);

score:1

You can use browserHistory :

  import { browserHistory } from "react-router";

  browserHistory.push({
     pathname: '/your/path'
  });

score:1

This answer is for react-router-v4.

If you want to redirect from the same component (not from some action) and this component is rendered by some route then you can use history object passed in the props.

componentDidMount(){
    if(this.state.some_param){
        this.props.history.push("/some_location")
    }
}

Best way is to create your own history object. You can use this history object in any action.

//history.js
import createHistory from 'history/createBrowserHistory'

export default createHistory()

then you can use this history in your router,

import history from "./history"

<Router history = {history}>
    //other code
</Router>

now you can use this history object anywhere for redirect,

axios.post('/some-route')
.then(res=>{
    history.push("/some_location")
})

const {Component} = React
const {render} = ReactDOM

const {Router, Link, Route, Switch, withRouter, Redirect} = ReactRouterDOM

const createHistory = History.createHashHistory

const myhistory = createHistory()

class App extends Component{
  redirectToHome(){
    myhistory.push("/home")
  }
  redirectToAbout(){
    myhistory.push("/about")
  }
  render(){
  return(
    <div>
      <Route path = "/home" component = {Home} />
      <Route path = "/about" component = {About} />
      <button onClick = {this.redirectToHome}>Redirect to home</button>
      <button onClick = {this.redirectToAbout}>Redirect to about</button>
    </div>
  )
  }
}

const Home = ()=>{
  return(
    <div>
      Home
    </div>
  )
}

const About = ()=>{
  return(
    <div>About</div>
  )
}


render(<Router history = {myhistory}><App/></Router>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<script src="https://unpkg.com/react-router-dom@4.1.1/umd/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/history/4.6.3/history.min.js"></script>
<div id="app"></div>


Related Query

More Query from same tag