I realized this has been asked before, please bear with me since I am still learning this. And I think I've tried all solutions in SO but without luck.
The issue is: When PrivateRoute
redirects to /sign_in
, it's not rendering the expected component (SignInForm
)
I have implemented a PrivateRoute
as following;
PrivateRoute.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { Route, Redirect, withRouter } from "react-router-dom";
// Simplified and still can reproduce the issue;
class PrivateRoute extends Route {
render () {
return (<Redirect to="/sign_in" />);
}
}
PrivateRoute.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
};
const mapStateToProps = state => {
return {
isAuthenticated: !!state.user.token
};
};
export default withRouter(connect(mapStateToProps)(PrivateRoute));
And this is where I use it;
index.js
<div className="content position-relative">
<div className="content-container font-nunito">
<Switch>
<Route path="/sign_in" component={SignInForm} />
<Route exact path="/" component={LandingPage} />
<PrivateRoute path="/trips" component={TestPage} />
</Switch>
</div>
</div>
Few points to add into the question:
- I confirm that Redirection does happen in
PrivateRoute
(I tested this by changing theto
param to another route, and I see the URI changes in my browser). - If I go directly to
/sign_in
, it works fine. The only problem is only when<Redirect>
does it. - My last resort will be to hackishly doing native browser redirect if this can not be solved. But, I'd like to avoid this if possible.
Here are my previous attempts that I have tried;
- Using
withRouter
in myPrivateRoute
- based on this answer - Sets the
PrivateRoute
not to bepure
- based on this answer - Tried importing
Redirect
andwithRouter
fromreact-router
instead ofreact-router-dom
- Installed
path-to-regexp@^2.4.0
- Use
push
inRedirect
- Based on this answer
I am currently using react-router-dom@5.2.0
and react@^16.2.0
.
Please help, any suggestions is appreciated. Let me know if I can provide more details.