Description
Reading this guide here
https://www.sitepoint.com/react-router-v4-complete-guide/
I was following it word for word, doing everything perfectly, up until the section about Protected Routes.
You say to put this in app.js
<Switch>
<Route exact path="/" component={Home} data={data}/>
<Route path="/category" component={Category}/>
<Route path="/login" component={Login}/>
<PrivateRoute authed={fakeAuth.isAuthenticated} path='/products' component = {Products} />
</Switch>
With this as the private route definition:
const PrivateRoute = ({component: Component, authed, ...rest}) => {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />} />
)
}
And.. I won't bother describing the Login component, it's what you put on the article.
Anyway, as its described in the article, it doesn't actually work. The log in
button on the Login route doesn't actually force the App.js
route to refresh or to change the value that it's passing as authed
prop to the PrivateRoute, so the redirect doesn't work when someone follows your guide.
So I downloaded the github code here and the code is drastically different, calculating the authed
status inside the PrivateRoute rather than passing it in as a prop. And that works!
Your article was good and informative, so I thought I'd contribute by helping you fix this small issue.