Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Private Route using react-router?

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.

like image 386
dhavalnc1 Avatar asked Dec 31 '22 17:12

dhavalnc1


1 Answers

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' />
        )} 
    />
}
like image 145
ravibagul91 Avatar answered Jan 03 '23 06:01

ravibagul91