1import React from 'react';
2import {
3 BrowserRouter,
4 Route,
5 Switch,
6 Redirect
7} from 'react-router-dom';
8import decode from 'jwt-decode';
9
10import Home from './Home';
11import Register from './Register';
12import Login from './Login';
13import PrivateComponent1 from './PrivateComponent1';
14import PrivateComponent2 from './PrivateComponent2';
15
16
17const isAuthenticated = () => {
18 const token = localStorage.getItem('token');
19 try {
20 if(token){
21 return true;
22 }
23 else{
24 return false;
25 }
26 } catch (error) {
27 return false;
28 }
29}
30
31function PrivateRoute({ component: Component, ...rest }) {
32 return (
33 <Route
34 {...rest}
35 render={props =>
36 isAuthenticated() ? (
37 <Component {...props} />
38 ) : (
39 <Redirect
40 to={{
41 pathname: "/login",
42 }}
43 />
44 )
45 }
46 />
47 );
48}
49
50export default () => (
51 <BrowserRouter>
52 <Switch>
53 <Route path="/" exact component={Home}/>
54 <Route path="/register" exact component={Register}/>
55 <Route path="/login" exact component={Login}/>
56 <PrivateRoute path="/private1/:id?" exact component={PrivateComponent1}/>
57 <PrivateRoute path="/private2" exact component={PrivateComponent2}/>
58 </Switch>
59 </BrowserRouter>
60);
1import React from 'react'
2import {Route, Redirect} from 'react-router-dom'
3
4const PrivateRoute = ({
5 component: Component,
6 isAuthenticated,
7 userLevel,
8 ...rest
9}) => (
10 <Route {...rest} component={(props)=>
11 isAuthenticated ? (
12 <Component {...props} />
13 ):(
14 <Redirect to="/login" />
15 )
16 } />
17)
18export default PrivateRoute
1const PrivateRoute = ({component: Component, ...rest}) => {
2 const {isAuthenticated} = rest;
3
4 return (
5 <Route {...rest} render={props => (
6 isAuthenticated ? (
7 <Component {...props}/>
8 ) : (
9 <Redirect to={{
10 pathname: '/login',
11 state: {from: props.location}
12 }}/>
13 )
14 )}
15 />
16 );
17};
18
19PrivateRoute.propTypes = {
20 isAuthenticated: PropTypes.bool.isRequired,
21};
22
23function mapStateToProps(state) {
24 return {
25 isAuthenticated: state.user.isAuthenticated,
26 };
27}
28
29export default connect(mapStateToProps)(PrivateRoute);
30