0

I have the following code :

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

but i dont understand how this works.. I call it like :

<PrivateRoute exact path = '/home' component={Home}></PrivateRoute>

it works , I just dont understand it. Where is props being passed in ? What is component: Component.

I would appreciate if someone could explain how this components works.

1
  • 1
    You pass the component in the render parameter in Route. So if your isAuthenticated method returns true then render will be provided whatever component you passed otherwise it get the Redirect component and hence redirect the user to login. If you pass any other props to the PrivateRoute those will be passed to the Route component using rest parameter (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…). Commented Mar 19, 2020 at 13:21

1 Answer 1

2

component: Component is object destructuring

You could re write it in the following way:

const PrivateRoute = (props) => {
  const Component = props.component;
  //shallow copy props, can also do {...props}
  const rest = Object.assign({},props);
  //delete component property from rest
  //  this will not affect props becaus of the shallow copy

The react-router Route component will take a props.component and renders that component with all props passed to Route minus the props.component.

You create a PrivateRoute that does the same but instead of rendering the component passed in props directly, it will render Route and pass a render prop to it that is a component created on the fly ()=>jsx. Route will render this component for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.