I'm fairly new to React development. As first project, I want to create a Website with integrated CMS-y features for a social club. I am using React, react-router-dom (v4) and firebase. I had to set up protected routes, and at the moment my Routes look as follows:
<Switch>
//other Routes with the same structure
<Route path="/events" component={Events} />
<Route path="/aboutus" component={AboutUs} />
//other Routes with the same structure
//Users have to be logged in from here on
<PrivateRoute path="/dashboard" component={Dashboard} />
<PrivateRoute path="/messages" component={Messages} />
//other PrivateRoutes with the same structure
<Route component={Home} />
</Switch>
PrivateRoute is recommended by the react-browser-dom-team and looks as follows:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
localStorage.loggedIn==="true" ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
My problem with it is that I have to save a loggedIn-flag in localStorage for the (separate) PrivateRoute to be able to check against it. I would like to use props (passed down to Main.js from App.js, where my firebaseOnAuthStateChange sits).
I then came up with simply writing protected Routes as:
<Route path="/dashboard" component={this.props.logged ? Dashboard : Login} />
This way, there's no redirect to the Login component when accessing /dashboard, but it shows up until the user logs in and is then shown the desired Component.
Now my question: I did quite some research on the web, and only found the "PrivateRoute"-solution... Is something wrong with my approach? And what's the standpoint on localStorage?