I have an component that it goBack to the previous page. I use that: this.props.history.goBack();
but I wanna that go back two levels. I have tried a lot of thing as this.props.history.goBack(-2);
but I do not achieve that. I am using ReactRouter v4.
How could I do that? Thank you.
Now according to line 6, if we go to the /about page, React Router first checks if the route contains a /. Since this condition is true, Home is being displayed again. Additionally, since the path contained the about keyword, then the About component is being rendered as well.
Photo by Sven Pieren on Unsplash. Traditionally, React has been used to build single-page web apps. However, if you insisted on building a React app with multiple pages or routes, the following process had to be done: Tell React to render the page according to the route that the user has navigated to.
So in a nutshell, by default, React Router will render all of the components that are subroutes of each other. To rectify this issue, we need to use the Switch component. According to React Router’s documentation, the Switch component essentially stops the whole process of going through all of the route paths as soon as it matches the URL.
import { useNavigate } from 'react-router-dom'; function goBack() { const navigate = useNavigate(); return <button onClick={() => navigate(-1)}>go back</button> } Share Follow answered yesterday ikuiku 7388 bronze badges
use this.props.history.go(-2)
as it's described in https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With