Skip to content Skip to sidebar Skip to footer

Passing Props In Protected Route Reactjs

I'm using protected routes in my reactjs application and I would like to know how to pass props in a protected route or if there is a more elegant way to solve my problem. The reas

Solution 1:

Declare your PrivateRoute outside of the class :

constPrivateRoute = ({ component: Component, handleLogout, isAuthenticated, ...rest }) => (
        <Route {...rest} render={(props) => (
            isAuthenticated === true
            ? <Component {...props} handleLogout={handleLogout} />
            : <Redirectto="/Login"/>
        )} />
);

Then pass handleLogout to your PrivateRoute props :

render() {
    return (
        <HashRouterbasename={BASE_URL}><divclassName="stories-module"><Routeexactpath={'/login'}
                     component={Login}
                /><PrivateRouteexactpath={'/Main/'}
                     component={Main}handleLogout={this.handleLogout}isAuthenticated={isAuthenticated}
                /></div></HashRouter>
    )
};

You may want to declare you PrivateRoute like below in order to pass any prop to the component by spreading all props :

constPrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
        <Route {...rest} render={(props) => (
            isAuthenticated === true
            ? <Component {...props} {...rest} />
            : <Redirectto="/Login"/>
        )} />
);

Solution 2:

Here is a more general solution to pass as many props to the component as you want:

render() {
  constPrivateRoute = ({ component: Component, data, ...rest }) => (
    <Route {...rest} render={(props) => (
        isAuthenticated === true
        ? <Component {...props} {...data} />
        : <Redirectto="/Login"/>
    )} />
  );

  return (
    <HashRouterbasename={BASE_URL}><PrivateRouteexactpath={'/login'}
        component={Login}data={{handleLogout=this.handleLogout,...someProp=this.prop
        }}
      /><PrivateRouteexactpath={'/Main/'}
        component={Main}data={{handleLogout=this.handleLogout,...someProp=this.prop
        }}
      /></HashRouter>
  );
}

Solution 3:

Add an extra prop to your PrivateRoute HOC

render() {
  constPrivateRoute = ({ component: Component, handleLogout, ...rest }) => (
    <Route {...rest} render={(props) => (
        isAuthenticated === true
        ? <ComponenthandleLogout={handleLogout} {...props} />
        : <Redirectto="/Login"/>
    )} />
  );

  return (
    <HashRouterbasename={BASE_URL}><PrivateRouteexactpath={'/login'}
        component={Login}handleLogout={this.handleLogout}
      /><PrivateRouteexactpath={'/Main/'}
        component={Main}handleLogout={this.handleLogout}
      /></HashRouter>
  );
}

Post a Comment for "Passing Props In Protected Route Reactjs"