Private Route

Question: Creating A PrivateRoute In React Using Class Component

Answer : 1

A Clear And Crescent Danger , Print Contents Of A File Only After Last Occurrence Of A Token? ,I Tried To Create A PrivateRoute In React Using Class Component, My Code:

render() { Const {component: Component, ...rest} = This.props; Return ( <Route {...rest} Render={props => ( LocalStorage.getItem('user') ? <Component {...props} /> : <Redirect To={{pathname: '/login'}} /> )} /> ) ); } 

Answer : 2

You Need To Wrap Your Route With <Switch> Tag

ReactDOM.render( <Provider Store={store}> <App> <Router> <div> <Switch> <PrivateRoute Exact Path="/"><Home /></PrivateRoute> // ... Other Private Routes <Route Path="/login" Component={Login} /> </Switch> </div> </Router> </App> </Provider>, Document.getElementById('root')); 

Set The Private Route To Not Be Pure:

export Default Connect(mapStateToProps, Null, Null, { Pure: False, })(PrivateRoute); 

Here It Is, I Hope It Helps

const App = (props) => { Return ( <Provider Store={store}> <Router> <div> <PrivateRoute Path="/secured" Component={Secured} IsAuthenticated={props.isAuthenticated} /> </div> </Router> </Provider> ); }; Const MapStateToProps = State => ({ IsAuthenticated: State.isAuthenticated }); Export Default Connect(mapStateToProps)(App); 

Then In My PrivateRoute

const PrivateRoute = ({ Component: Component, IsAuthenticated, ...rest}) => ( <Route {...rest} Render={props => ( IsAuthenticated ? ( <Component {...props} /> ) : (<Redirect To={{ Pathname: '/login', State: { From: Props.location} }} />) )} /> ); Export Default PrivateRoute; 

I Managed To Get This Working Using The rest Parameter To Access The Data From mapStateToProps:

const PrivateRoute = ({component: Component, ...rest}) => { Const {isAuthenticated} = Rest; Return ( <Route {...rest} Render={props => ( IsAuthenticated ? ( <Component {...props}/> ) : ( <Redirect To={{ Pathname: '/login', State: {from: Props.location} }}/> ) )} /> ); }; PrivateRoute.propTypes = { IsAuthenticated: PropTypes.bool.isRequired, }; Function MapStateToProps(state) { Return { IsAuthenticated: State.user.isAuthenticated, }; } Export Default Connect(mapStateToProps)(PrivateRoute); 

I Found A 3rd Solution, Though It’s Unclear To Me If It Is Really A Better Solution Than WithRouter, Using Higher Order Component. You Connect Your Higher-order Component To The Redux Store, And Now Your Route Doesn’t Give A Damn About What It Renders, The HOC Deals With It.

import Notlogged From "./Notlogged"; Function Isloggedhoc({ Wrap: Component, Islogged, ...props }) { Return Islogged ? <Component {...props} /> : <Notlogged {...props} />; } Const MapState = (state, Ownprops) => ({ Islogged: State.logged, ...ownprops }); Export Default Connect(mapState)(Isloggedhoc); 

in Your App.js

<Route Path="/PrivateRoute" Render={props => <Isloadedhoc Wrap={Mycomponent} />} /> 

You Could Even Make A Curried Function To Shorten It A Bit:

function IsLogged(component) { Return Function(props) { Return <Isloadedhoc Wrap={component} {...props} />; }; } 

Using It Like That:

<Route Path="/PrivateRoute" Render={isLogged(Mycomponent)} /> 

Instead Of Passing IsAuthenticated To Every < PrivateRoute> Component, You Just Need To Get IsAuthenticated From State In < PrivateRoute> Itself.

import React From 'react'; Import {Route, Redirect, WithRouter} From 'react-router-dom'; Import {connect} From 'react-redux'; // IsAuthenticated Is Passed As Prop Here Const PrivateRoute = ({component: Component, IsAuthenticated , ...rest}) => { Return <Route {...rest} Render={ Props => { Return IsAuthenticated ? ( <Component {...props} /> ) : ( <Redirect To={{ Pathname: "/login", State: {from: Props.location} }} /> ) } } /> }; Const MapStateToProps = State => ( { // IsAuthenticated Value Is Get From Here IsAuthenticated : State.auth.isAuthenticated } ); Export Default WithRouter(connect( MapStateToProps, Null, Null, {pure: False} )(PrivateRoute)); 

Answer : 3

See More Details

 ANYCODING SOLVED THIS ISSUE 

Answer : 4

See More Details

 ANYCODING SOLVED THIS ISSUE 

Answer : 5

Hopefully, This Tutorial Can Give You More Insight Into Different Types Of Routes And How To Use Them.,React Router Is One Of The Most Important Components Of React Ecosystem. In This Tutorial, We Will Learn How To Build Different Types Of Routes Including Private, Public, And Restricted Routes. For A Quick Demonstration, We Will Build A Simple Application With Following Components:,Finally Come To The , We Can Conveniently Declare All The Routes We Want Without A Sweat.

Private Route

PrivateRoute Component Is The Blueprint For All Private Routes In The Application. If The User Is Logged In, Go On And Display The Component In Question; Otherwise, Redirect The User To Sign-in Page. Additionally, We Can Define The Logic Of isLogin Utility Function Separately In utils Folder.

isLogin

Private Route

PrivateRoute Component Is The Blueprint For All Private Routes In The Application. If The User Is Logged In, Go On And Display The Component In Question; Otherwise, Redirect The User To Sign-in Page. Additionally, We Can Define The Logic Of isLogin Utility Function Separately In utils Folder.

utils

Public Route

On The Other Hand, PublicRoute Component Is The Model For All Public And Restricted Routes. The Difference Between Two Types Is Defined If restricted Props. restricted = False Meaning That Route Is Public; Or Else, It Is Restricted.

restricted

Public Route

On The Other Hand, PublicRoute Component Is The Model For All Public And Restricted Routes. The Difference Between Two Types Is Defined If restricted Props. restricted = False Meaning That Route Is Public; Or Else, It Is Restricted.

restricted = False

Put All Together In The <App>

Finally Come To The <App>, We Can Conveniently Declare All The Routes We Want Without A Sweat.

<App>

Answer : 6

The Path To That Component /page/profile For Example ,I Will Create A Simple Jsx Or Tsx Component (works For React JS Or Typescript) That Wraps Around The Route Component From The React-router-dom Library. It Will Check For My Given Condition First, If That’s True, It Will Render That Component Like It’s Supposed To Do, Otherwise It Will Redirect Me To The Login Page., A Working React Application With Your Routes Configured And Ready To Use.

<Route Path="/page/home" Component={Home} Exact /> <Route Path="/page/news" Component={News} Exact /> <Route Path="/page/login" Component={Login} Exact /> <Route Path="/page/profile" Component={Profile} Exact /> <Redirect From="/" To="/page/home" Exact /> 

import React From "react"; Import { Route, Redirect } From "react-router-dom"; Const PrivateRoute: React.FC<{ Component: React.FC; Path: String; Exact: Boolean; }> = (props) => { Const Condition = PerformValidationHere(); Return Condition ? (<Route Path={props.path} Exact={props.exact} Component={props.component} />) : (<Redirect To="/page/login" />); }; Export Default PrivateRoute; 

<Route Path="/page/home" Component={Home} Exact /> <Route Path="/page/news" Component={News} Exact /> <Route Path="/page/login" Component={Login} Exact /> <PrivateRoute Path="/page/profile" Component={Profile} Exact /> <Redirect From="/" To="/page/home" Exact /> 

Answer : 7

Provided You Are Using React-router-dom The Code Should Still Work For You. I Will Be Linking The Github Repo ASAP,This Tutorial Follows Tutorial 1,Add, Commit, Push, And Pull Request Your New Private Route

import React From 'react' Const AdminHome = () => { Return ( <div> <h1>Welcome Home Admin</h1> </div> ) } Export Default AdminHome 

const PrivateRoute = ({ Component: Component, ...rest }) = { <R {...rest} Render={props => LocalStorage.getItem('token') ? ( <Component {...props} /> ): ( <RD To='/' /> ) } [/](file:///)> ); Export Default PrivateRoute; 

Answer : 8

It Always Happens When You’re Building A React App And Configuring Your Routes, You Find Out That You Don’t Want Your Routes To Be All Public All The Time. Perhaps You Want To Make Some Routes Accessible Only For Authenticated Users.,In This Boilerplate You Can Easily Configure Private & Public Routes In Your Project, Clone It From The Above Given GitHub URL.,URL: https://github.com/sreenathkspanikker/react-private-public-routes.git

Route.js

import React, { UseState, UseMemo } From "react"; Import { UserContext } From "./hooks/UserContext"; Import { BrowserRouter, Switch } From 'react-router-dom'; Import { Login, Home, PageOne, PageTwo, NoMatch } From './pages/' Import PublicRoute From './hooks/PublicRoute' Import PrivateRoute From './hooks/PrivateRoute' Function AppRouter() { Const [user, SetUser] = UseState(null); Const Value = UseMemo(() => ({ User, SetUser }), [user, SetUser]); Return ( <BrowserRouter> <UserContext.Provider Value={value}> <Switch> <!-- PUBLIC ROUTE --> <PublicRoute Restricted={true} Component={Login} Path="/" Exact /> <!-- PRIVATE ROUTE --> <PrivateRoute Component={Home} Path="/home" Exact /> <PrivateRoute Component={PageOne} Path="/page-1" Exact /> <PrivateRoute Component={PageTwo} Path="/page-2" Exact /> <PrivateRoute Component={NoMatch} Path="*" /> <PublicRoute Component={NoMatch} Path="*" /> </Switch> </UserContext.Provider> </BrowserRouter> ); } Export Default AppRouter; 

PrivateRoute.js

import React From 'react'; Import { Route, Redirect } From 'react-router-dom'; Import { IsLogin } From '../middleware/auth'; Const PrivateRoute = ({ Component: Component, ...rest }) => ( // Show The Component Only When The User Is Logged In // Otherwise, Redirect The User To /signin Page <Route {...rest} Render={props => (isLogin() ? <Component {...props} /> : <Redirect To="/" />)} /> ) Export Default PrivateRoute; 

PublicRoute.js

import React From 'react'; Import { Route, Redirect } From 'react-router-dom'; Import { IsLogin } From '../middleware/auth'; Const PublicRoute = ({ Component: Component, Restricted, ...rest }) => ( 
		Posted in Uncategorized