I want to make secure routes using authentication. I have defined the routes in App.jsx file. I am using "Route" to define which component to render.
In App.jsx
<Route
path='/dashboard'
exact={true}
render={(props) => <Dashboard {...props} user={user}
handleChildFunc={this.handleChildFunc}/>}
/>
The above code works without any issue. I want to make that secured like below.
<PrivateRoute
path='/dashboard'
exact={true}
render={(props) => <Dashboard {...props} user={user}
handleChildFunc={this.handleChildFunc}/>}
/>
In PrivateRoute.jsx
const PrivateRoute = ( props ) => {
const user = "token from cookie"; // i will fetch token stored in cookie
if(user !== null) {
return <Route />;
}
else {
return <Redirect to="login" />
}
}
If the token is present, render a component. Otherwise, redirect to /login.
You can have your PrivateRoute
like,
<PrivateRoute
path='/dashboard'
exact={true}
component={Dashboard}
handleChildFunc={this.handleChildFunc}
/>
const PrivateRoute = ({ component: Component, handleChildFunc, ...rest }) => {
const user = "token from cookie";
return <Route {...rest} render={(props) => (
user !== null
? <Component {...props} user={user} handleChildFunc={handleChildFunc}/>
: <Redirect to='/login' />
)}
/>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With