Conditional / secure communication-router-dom component

I am new to React development. As a first project, I want to create a website with built-in CMS-y functionality for a social club. I am using React, react-router-dom (v4) and firebase. I needed to set up secure routes and at the moment my routes look like this:

<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 response-browser-dom command and looks like this:

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
 localStorage.loggedIn==="true" ? (
  <Component {...props}/>
) : (
  <Redirect to={{
    pathname: '/login',
    state: { from: props.location }
  }}/>
)
)}/>
)

      

My problem is that I have to store the loggedIn flag in localStorage for the (separate) PrivateRoute in order to be able to check it. I would like to use props (passed to Main.js from App.js where my firebaseOnAuthStateChange sits).

Then I came up with just writing protected routes as:

<Route path="/dashboard" component={this.props.logged ? Dashboard : Login} />

      

This way, when the control panel is accessed, the login item is not redirected, but is displayed until the user logs in and displays the desired component.

Now my question . I did some research on the internet and only found the "PrivateRoute" solution ... Is there something wrong with my approach? What's the point of view of localStorage?

+3


source to share





All Articles