C:\Users\Administrator\Desktop\typescript\src\guards\AuthenticatedGuard\index.tsx
import React, { Component } from 'react';
import { Route, RouteProps, Redirect, RouteComponentProps } from 'react-router-dom';
import { connect } from 'react-redux';
import * as interfaces from './../../interface';
function AuthenticatedGuard(props: interfaces.Props) {
const { isAuthenticated, component: Component, ...rest } = props;
return (
<Route {...rest}
render = { props => {
if (!isAuthenticated) {
return <Redirect to="/login" />
}
return <Component {...props} />
}}
/>
)
}
const mapStateToProps = (state: any) => ({
isAuthenticated: false
})
const mapDispatchToProps = (dispatch: any) => ({
})
export default connect(mapStateToProps, mapDispatchToProps)(AuthenticatedGuard);
C:\Users\Administrator\Desktop\start\src\index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
C:\Users\Administrator\Desktop\start\src\routes\index.tsx
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import HomeRoutes from './HomeRoutes';
import LoginRoutes from './LoginRoutes';
function Routes() {
return (
<Router>
<HomeRoutes />
<LoginRoutes />
</Router>
)
}
export default Routes;
C:\Users\Administrator\Desktop\start\src\routes\HomeRoutes.tsx
import React from 'react';
import { Switch } from 'react-router-dom';
import { PATH } from './../constants/paths';
import Home from './../pages/Home';
import AuthenticatedGuard from './../guards/AuthenticatedGuard';
function HomeRoutes() {
return (
<Switch>
<AuthenticatedGuard exact={true} path={PATH.HOME} component={Home} />
</Switch>
)
}
export default HomeRoutes;
C:\Users\Administrator\Desktop\start\src\routes\LoginRoutes.tsx
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { PATH } from './../constants/paths';
import Login from './../pages/Login';
function LoginRoutes() {
return (
<Switch>
<Route path={PATH.LOGIN} component={Login} />
</Switch>
)
}
export default LoginRoutes;
C:\Users\Administrator\Desktop\start\src\guards\AuthenticatedGuard\index.tsx
import React, { Component } from 'react';
import { Route, RouteProps, Redirect, RouteComponentProps } from 'react-router-dom';
import { connect } from 'react-redux';
import * as interfaces from './../../interface';
function AuthenticatedGuard(props: interfaces.Props) {
const { isAuthenticated, component: Component, ...rest } = props;
return (
<Route {...rest}
render = { props => {
if (!isAuthenticated) {
return <Redirect to="/login" />
}
return <Component {...props} />
}}
/>
)
}
const mapStateToProps = (state: any) => ({
isAuthenticated: false
})
const mapDispatchToProps = (dispatch: any) => ({
})
export default connect(mapStateToProps, mapDispatchToProps)(AuthenticatedGuard);