I am learning React. But I am familiar with Vue. In Vue with the Vue Router, we can have an array of objects based routing like,
JavaScript
x
18
18
1
const routes = [
2
{
3
name : "Login",
4
path : "/login",
5
component : ()=> import('views/Login.vue') //for lazy loading
6
meta : {
7
auth : false // this means no authentication needed for this particular route
8
}
9
},
10
{
11
name : "Dashboard",
12
path : "/dashboard",
13
component : ()=> import('views/Dashboard.vue') //for lazy loading
14
meta : {
15
auth : true // this means authentication needed for this particular route if the user is not authenticated, they will be redirected to login page
16
},
17
}]
18
What I tried so far is as below :
Login.jsx
JavaScript
1
9
1
const Login = () => {
2
const onClick = () => {
3
localStorage.setItem("token", "admin");
4
};
5
return <button onClick={onClick}>Login</button>;
6
};
7
8
export default Login;
9
Dashboard.jsx
JavaScript
1
6
1
const Dashboard = () => {
2
return <h1>Dashboard</h1>;
3
};
4
5
export default Dashboard;
6
App.js
JavaScript
1
56
56
1
import React, { Fragment } from "react";
2
import { Redirect, Route, Switch } from "react-router-dom";
3
import Dashboard from "./Dashboard";
4
import Login from "./Login";
5
6
const App = () => {
7
const routes = [
8
{
9
path: "/login",
10
component: Login,
11
auth: false,
12
},
13
{
14
path: "/dashboard",
15
component: Dashboard,
16
auth: true,
17
},
18
{
19
path: "/example",
20
component: Example,
21
auth: true,
22
},
23
];
24
return (
25
<>
26
<Switch>
27
{routes.map((route, index) => {
28
return (
29
<Fragment key={index}>
30
{route.auth ? (
31
<>
32
<Route
33
exact
34
path={`${route.path}`}
35
component={route.component}
36
/>
37
</>
38
) : (
39
<>
40
<Route
41
exact
42
path={`${route.path}`}
43
component={route.component}
44
/>
45
</>
46
)}
47
</Fragment>
48
);
49
})}
50
</Switch>
51
</>
52
);
53
};
54
55
export default App;
56
But in the above approach, I am always getting redirected to “/login”. Is there anyways to fix this? Thanks in advance
Advertisement
Answer
Maybe this React-View-Router package help you. Instead of react-router-dom, try this package, and you can follow vue-router like syntax