Passing props in protected route reactjs
Declare your PrivateRoute
outside of the class :
const PrivateRoute = ({ component: Component, handleLogout, isAuthenticated, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} handleLogout={handleLogout} />
: <Redirect to="/Login"/>
)} />
);
Then pass handleLogout
to your PrivateRoute
props :
render() {
return (
<HashRouter basename={BASE_URL}>
<div className="stories-module">
<Route
exact
path={'/login'}
component={Login}
/>
<PrivateRoute
exact
path={'/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 :
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} {...rest} />
: <Redirect to="/Login"/>
)} />
);
Here is a more general solution to pass as many props to the component as you want:
render() {
const PrivateRoute = ({ component: Component, data, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} {...data} />
: <Redirect to="/Login"/>
)} />
);
return (
<HashRouter basename={BASE_URL}>
<PrivateRoute
exact
path={'/login'}
component={Login}
data={{
handleLogout=this.handleLogout,
...
someProp=this.prop
}}
/>
<PrivateRoute
exact
path={'/Main/'}
component={Main}
data={{
handleLogout=this.handleLogout,
...
someProp=this.prop
}}
/>
</HashRouter>
);
}
Add an extra prop to your PrivateRoute
HOC
render() {
const PrivateRoute = ({ component: Component, handleLogout, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component handleLogout={handleLogout} {...props} />
: <Redirect to="/Login"/>
)} />
);
return (
<HashRouter basename={BASE_URL}>
<PrivateRoute
exact
path={'/login'}
component={Login}
handleLogout={this.handleLogout}
/>
<PrivateRoute
exact
path={'/Main/'}
component={Main}
handleLogout={this.handleLogout}
/>
</HashRouter>
);
}