DEV Community

Cover image for How does ({component: Component}) work in PrivateRoute?
Pere Sola
Pere Sola

Posted on

How does ({component: Component}) work in PrivateRoute?

I am practicing an auth and authorization engine with Firebase. I found a good YouTube video and they use the syntax below for a Private Route:

<Switch>

    <PrivateRoute exact path='/' component={Dashboard} />
    <Route path='/signup' component={Signup} />
    <Route path='/login' component={Login} />
</Switch>
Enter fullscreen mode Exit fullscreen mode

and then

export default function PrivateRoute({ component: Component, ...rest }) {
    const { currentUser } = useAuth();
    return (
        <Route
            {...rest}
            render={(props) => {
                return currentUser ? (
                    <Component {...props} />
                ) : (
                    <Redirect to='/login' />
                );
            }}
        ></Route>
    );
}
Enter fullscreen mode Exit fullscreen mode

If a user is logged in, show the component, if the user is not logged in, redirect to login. The syntax {component: Component} kept me wondering... how does it work? I get it that the Component arrives within the component variable, but then, how does it translate into the Component we can use to render content?

Did a bit of Googling, and I found this:

If I’m not mistaken, the reason that the component prop is reassigned to the Component identifier is because the JSX attempts to create a component DOM element (which doesn’t exist) instead of a React component—a capitalised identifier is required for creating a React component.

Hmm, I didn't quite understand and I thought... is that complicated??

I asked in Stack Overflow and it is much more simple than that: it is vanilla JS!

The syntax {component: Component} is just taking whatever arrives as component, unpacking it as MDN docs call it, and assigning it to a new variable, Component.

As simple as that. Now I know.

Top comments (0)