Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  67] [ 6]  / answers: 1 / hits: 5250  / 4 Years ago, sun, july 12, 2020, 12:00:00

In a React App, I use Router like this:


let path='/';
if(condition){
path='/dashboard'
}else if(condition){
path='/login'
}

<Router>
<Redirect to={path} />
<Switch>
<Route path="/dashboard"><Dashboard /></Route>
<Route path="/login"><Login /></Route>
</Switch>
</Router>

This works fine. But I want to implement a Back Button in each page to move along pages. I do this:


// The login.jsx component
function Post(props) {
return (
<div>
<button type="button" onClick={() => props.history.goBack()}>
Go back
</button>
</div>
);
}

But I get this error:


Uncaught TypeError: Cannot read property 'goBack' of undefined

Then I follow another approach. I use useHistory:


import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
Link,
useHistory,
} from "react-router-dom";

// The login.jsx component
function Post(props) {
let history = useHistory();

return (
<div>
<button type="button" onClick={() => history.goBack()}>
Go back
</button>
</div>
);
}

And this time when I click on the Go Back button, nothing happens!


If I do this procedures with <Link/> it works fine. But when I use <Redirect /> approach, it doesn't work. is there any alternative to my redirect approach? or is there any solution to current approach? thanks.


More From » reactjs

 Answers
1

For redirects to be included in the history, use push


<Redirect push to={path} />

More information here from the docs


[#3209] Thursday, July 9, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;