简体   繁体   中英

How to pass props to child components when using protected routes?

I'm currently developing a 'Train Ticket Reservation System' using ReactJS. Since users should login to access the services, I have used protected routes to render some components. Instead of using the default . So far I know how to send props with using the render method. I want to know how to send props when using protected routes. Since the render method doesn't work with that.

This is my implementation of the protected route.

import React from 'react';  
import auth from './auth';  
import {Route, Redirect} from 'react-router-dom';  

const ProtectedRoute = ({component: Component, ...rest}) => {  

    return(  
        <Route {...rest} render={props => {  

            if(auth.isAuthenticated()){  
                console.log(auth.isAuthenticated())  
                return <Component {...props}/>  
            }  
            else{  
                return <Redirect to={  
                    {  
                        pathname: '/',  
                        state:{  
                            from: props.location  
                        }  
                    }  
                } />  
            }  
            }} />  
    );  

};  

export default ProtectedRoute; 

This is how I used protected route for navigation

<ProtectedRoute  exact path="/Home/AboutUs" component={AboutUs}/>

You can just pass props to the ProtectedRoute component.

ie

<ProtectedRoute exact page="Home" path="/Home/AboutUs" component={AboutUs}/>

To get the page props in the Component

Since you have used destructuring.

const ProtectedRoute = ({component: Component, ...rest}) => { ..... }

Except component props the remaining props are assigned to the variable rest after the spread operator.

So you can get the props from the variable rest which is an object.

<Component {...props} pageProps={rest.page} />  // pageProps="Home"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM