score:151
I think the issue is with binding:
constructor(props){
super(props);
this.goBack = this.goBack.bind(this); // i think you are missing this
}
goBack(){
this.props.history.goBack();
}
.....
<button onClick={this.goBack}>Go Back</button>
As I have assumed before you posted the code:
constructor(props) {
super(props);
this.handleNext = this.handleNext.bind(this);
this.handleBack = this.handleBack.bind(this); // you are missing this line
}
score:0
Try:
this.props.router.goBack()
score:0
Simply use
<span onClick={() => this.props.history.goBack()}>Back</span>
score:0
Hope this will help someone:
import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';
interface Props {
history: History;
}
@withRouter
export default class YourComponent extends React.PureComponent<Props> {
private onBackClick = (event: React.MouseEvent): void => {
const { history } = this.props;
history.goBack();
};
...
score:0
Maybe this can help someone.
I was using history.replace()
to redirect, so when i tried to use history.goBack()
, i was send to the previous page before the page i was working with.
So i changed the method history.replace()
to history.push()
so the history could be saved and i would be able to go back.
score:0
I am not sure if anyone else ran into this problem or may need to see this. But I spent about 3 hours trying to solve this issue:
I wanted to implement a simple goBack() on the click of a button. I thought I was off to a good start because my App.js was already wrapped in the Router and I was importing { BrowserRouter as Router } from 'react-router-dom'; ... Since the Router element allows me to assess the history object.
ex:
import React from 'react';
import './App.css';
import Splash from './components/Splash';
import Header from './components/Header.js';
import Footer from './components/Footer';
import Info from './components/Info';
import Timer from './components/Timer';
import Options from './components/Options';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Header />
<Route path='/' component={Splash} exact />
<Route path='/home' component={Info} exact />
<Route path='/timer' component={Timer} exact />
<Route path='/options' component={Options} exact />
<Footer />
</Router>
);
}
export default App;
BUT the trouble was on my Nav (a child component) module, I had to 'import { withRouter } from 'react-router-dom';' and then force an export with:
export default withRouter(Nav);
ex:
import React from 'react';
import { withRouter } from 'react-router-dom';
class Nav extends React.Component {
render() {
return (
<div>
<label htmlFor='back'></label>
<button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
<label htmlFor='logOut'></label>
<button id='logOut' ><a href='./'>Log-Out</a>
</button>
</div>
);
}
}
export default withRouter(Nav);
in summary, withRouter was created because of a known issue in React where in certain scenarios when inheritance from a router is refused, a forced export is necessary.
score:0
You can use history.goBack()
in functional component. Just like this.
import { useHistory } from 'react-router';
const component = () => {
const history = useHistory();
return (
<button onClick={() => history.goBack()}>Previous</button>
)
}
score:2
UPDATE 2022 w V6
navigate(-1)
to omit the current page from history:
navigate(-1, { replace: true })
score:4
If using react hooks just do:
import { useHistory } from "react-router-dom";
const history = useHistory();
history.go(-1);
score:5
Can you provide the code where you use this.props.history.push('/Page2');
?
Have you tried the goBack() method?
this.props.history.goBack();
It's listed here https://reacttraining.com/react-router/web/api/history
With a live example here https://reacttraining.com/react-router/web/example/modal-gallery
score:7
Here is the cleanest and simplest way you can handle this problem, which also nullifies the probable pitfalls of the this keyword
. Use functional components:
import { withRouter } from "react-router-dom";
wrap your component
or better App.js
with the withRouter()
HOC
this makes history
to be available "app-wide". wrapping your component only makes history available for that specific
component``` your choice.
So you have:
export default withRouter(App);
In a Redux environment
export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), );
you should even be able to userhistory
from your action creators this way.
in your component
do the following:
import {useHistory} from "react-router-dom";
const history = useHistory(); // do this inside the component
goBack = () => history.goBack();
<btn btn-sm btn-primary onclick={goBack}>Go Back</btn>
export default DemoComponent;
Gottcha useHistory
is only exported from the latest v5.1 react-router-dom
so be sure to update the package. However, you should not have to worry.
about the many snags of the this keyword
.
You can also make this a reusable component to use across your app.
function BackButton({ children }) {
let history = useHistory()
return (
<button type="button" onClick={() => history.goBack()}>
{children}
</button>
)
}```
Cheers.
score:11
Each answer here has parts of the total solution. Here's the complete solution that I used to get it to work inside of components deeper than where Route was used:
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
^ You need that second line to import function and to export component at bottom of page.
render() {
return (
...
<div onClick={() => this.props.history.goBack()}>GO BACK</div>
)
}
^ Required the arrow function vs simply onClick={this.props.history.goBack()}
export default withRouter(MyPage)
^ wrap your component's name with 'withRouter()'
score:18
For use with React Router v4 and a functional component anywhere in the dom-tree.
import React from 'react';
import { withRouter } from 'react-router-dom';
const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;
export default withRouter(GoBack);
score:65
UPDATED:
Now we have hook, so we can do it easily by using useHistory
const history = useHistory()
const goBack = () => {
history.goBack()
}
return (
<button type="button" onClick={goBack}>
Go back
</button>
);
ORIGINAL POST:
this.props.history.goBack();
This is the correct solution for react-router v4
But one thing you should keep in mind is that you need to make sure this.props.history is existed.
That means you need to call this function this.props.history.goBack();
inside the component that is wrapped by < Route/>
If you call this function in a component that deeper in the component tree, it will not work.
EDIT:
If you want to have history object in the component that is deeper in the component tree (which is not wrapped by < Route>), you can do something like this:
...
import {withRouter} from 'react-router-dom';
class Demo extends Component {
...
// Inside this you can use this.props.history.goBack();
}
export default withRouter(Demo);
Source: stackoverflow.com
Related Query
- React Router - How to Determine If Back button was hit?
- How to intercept back button in a React SPA using function components and React Router v5
- How to controling browser back button with react router dom v6?
- How to use React Router to go back to previous page
- How to re-render or refresh previous screen when going back using react router flux
- How do I go back to home page if previous path don't exists react router v6
- How to go back to react router v5 from react router v6 for nested dashboard?
- How to go back to the previous url without query params in react router
- How to push to History in React Router v4?
- React Router v4 - How to get current route?
- How to implement authenticated routes in React Router 4?
- How to set the DefaultRoute to another Route in React Router
- How to redirect in React Router v6?
- How to use React Router with Electron?
- How to fetch the new data in response to React Router change with Redux?
- How to navigate on path by button click in react router v4?
- How to mock history.push with the new React Router Hooks using Jest
- React Router - how to constrain params in route matching?
- How to redirect from axios interceptor with react Router V4?
- How to let react router respond with 404 status code?
- How to use React Router with Laravel?
- How to configure webpack dev server with react router dom v4?
- How to hide navbar in login page in react router
- How to generate sitemap with react router
- React router, how to restore state after browser back button?
- React router and this.props.children - how to pass state to this.props.children
- How to use context api with react router v4?
- How to make react router work with static assets, html5 mode, history API and nested routes?
- How to use React Router on top of Rails router (not using react-rails gem)?
- How to know if react-router can go back to display back button in react app
More Query from same tag
- Not able to get the request body in the node API
- react how to setup private routes that can only be accessed when someone is signed in?
- Nodejs : how to redirect subdomains to ports?
- Using react.useEffect and mobx.autorun together
- data not rendering using flat list
- How can I allow just one input selection in react?
- Rendering grid in React using lodash
- How to show ISO date format in a date input field - React
- Customize material-ui popover
- Expected an assignment or function call and instead saw an expression no-unused-expressions - how to fix this CI error?
- How to switch scss/css file at runtime or switch theme in reactjs
- Express Go To Direct Link In React Router/React
- How to fix "... is not a function" error?
- Importing React = 'SyntaxError: Cannot use import statement outside a module'
- How to fix a conditional problem in react
- How to deploy react app to shared hosting thats running nodeJS?
- How could i send the setStateAction in useState React
- Sending multiple values to stored procedure and use it in IN operator
- How pass a array and setArray in value of provider (React, Typescript, Context)
- Firebase JavaScript - Mapping values from array only display last item
- Setup Airbrake-js with a ReactJS app and webpack
- react js : display items using map method
- React Validation Max Range Using Formik
- Background Image Not Displaying in React App
- onSubmit not working inside react-bootstrap nav dropdown
- Is there a way to prevent toggling of input text when hiding an element
- How to imitate PaddingTop with Grid Material UI and fill empty rows from the top?
- Typescript JSDoc ...Rest type syntax
- How to initiallize values in a redux form using mapStateToProps from a custom JSON as prop?
- Pass id to every <Link>