Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create PrivateRoute with React-Router-Dom

I have seen lots of use cases about how people create private route with react-router-dom. It usually looks like this:

const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest}) =>  (
    <Route {...rest} render={props => (
        isAuthenticated ?
            <Component {...props} />
        : <Redirect to="/signin" />
    )} />
);

And my question is: If I can use this way to do the same thing?

const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest }) => (
    isAuthenticated ? <Route {...rest} render={props => <Component {...props}/>}/> :<Redirect to="/signin" />
)

It seems working when I ran the code. But I still want to know why we do the condition check at the first way of writing? Is the second way of writing incorrect? If so, why? Thank you!

like image 241
James Yang Avatar asked Feb 04 '26 04:02

James Yang


1 Answers

It's just a preference thing, either is fine and both will work. you can also make it even shorter and more readable like this if you like

const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest }) => (
    isAuthenticated ? <Component {...rest} /> : <Redirect to="/signin" />
)

and then render like so:

<PrivateRoute
   exact
   component={ComponentToRender}
   path="/path"
   aProp={'aProp'}
/>
like image 52
Red Baron Avatar answered Feb 06 '26 23:02

Red Baron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!