React Private Routing through id

So I’m using PrivateRoute in React to serve some components. Everything’s been working fine until I specified the exact path like below:

<PrivateRoute exact path="/info/:id" render={(props) => <BookInfo {...props} />} />

The above path works fine if I serve it normally using Route but routing though PrivateRoute gives me the following error.
enter image description here

PrivateRoute.js

import React from 'react'
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';

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

const mapStateToProps = state => ({
    auth: state.auth
})

export default connect (mapStateToProps)(PrivateRoute);

I don’t know what’s causing this, some help is much appreciated.

30 thoughts on “React Private Routing through id”

  1. Issue

    Your PrivateRoute component is expecting a component prop to be passed, it doesn’t handle the other props a Route component handles.

    const PrivateRoute = ({
      component: Component, // <-- only handles component prop
      auth, ...rest
    }) => (
      <Route {...rest} render={ props => 
        auth.isAuthenticated === true ?
        (<Component {...props}/>) : (<Redirect to ='/login'/>)}/>
    )
    

    Solution

    Pass your BookInfo on the component prop so it is piped through.

    <PrivateRoute exact path="/info/:id" component={BookInfo} />
    

    Refactor your PrivateRoute component to render either a Route with all the props passed to it, or the Redirect component.

    const PrivateRoute = ({ auth, ...props }) => auth.isAuthenticated ? (
        <Route {...props} />
      ) : (
        <Redirect to ='/login'/>
      );
    
    Reply

Leave a Comment