1

I am using react-router v.4 and I would like to perform some go back function.

My current code looks as below:

<HashRouter>
       <Switch>
            <Route exact path='/' component={Main}/>
            <Route path='/secondview' component={SecondView}/>
            <Route path='/traineeships' render={()=>(<Traineeship rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Route path='/information-filter' render={()=>(<InformationFilter rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Route path='/find-work' render={()=>(<FindWork rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Route path='/information-job' render={()=>(<InformationJob rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Redirect from='*' to='/' />
       </Switch>

I tried several options like this.props.history.go(-1) on other components but I was getting undefined errors.

Anyone knows how to perform go back function in my case?

Anh Pham
  • 645
  • 6
  • 20
Mizlul
  • 1,802
  • 2
  • 27
  • 81

2 Answers2

7

You could use withRouter, if you need to access history object:

import React from 'react'
import { withRouter } from 'react-router'

class SecondView extends React.Component {
  render() {
    return (
      <button onClick={() => this.props.history.go(-1)} />
    )
  }
}

const SecondViewnWithRouter = withRouter(SecondView)

withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

Evgeny Timoshenko
  • 2,561
  • 4
  • 29
  • 49
0

Depending on the the version of react-router (in this case 3.0) you could enable BrowserHistory firstand do:

const BrowserHistory = require('react-router/lib/BrowserHistory').default;

and you could use it in JSX:

<button onClick={BrowserHistory.goBack}>Back</button>

And this code in your App file:

<Router history={BrowserHistory}>
    <Route path="/" component={App} />
</Router>
GibboK
  • 64,078
  • 128
  • 380
  • 620