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,
const routes = [ { name : "Login", path : "/login", component : ()=> import('views/Login.vue') //for lazy loading meta : { auth : false // this means no authentication needed for this particular route } }, { name : "Dashboard", path : "/dashboard", component : ()=> import('views/Dashboard.vue') //for lazy loading meta : { auth : true // this means authentication needed for this particular route if the user is not authenticated, they will be redirected to login page }, }]
What I tried so far is as below :
Login.jsx
const Login = () => { const onClick = () => { localStorage.setItem("token", "admin"); }; return <button onClick={onClick}>Login</button>; }; export default Login;
Dashboard.jsx
const Dashboard = () => { return <h1>Dashboard</h1>; }; export default Dashboard;
App.js
import React, { Fragment } from "react"; import { Redirect, Route, Switch } from "react-router-dom"; import Dashboard from "./Dashboard"; import Login from "./Login"; const App = () => { const routes = [ { path: "/login", component: Login, auth: false, }, { path: "/dashboard", component: Dashboard, auth: true, }, { path: "/example", component: Example, auth: true, }, ]; return ( <> <Switch> {routes.map((route, index) => { return ( <Fragment key={index}> {route.auth ? ( <> <Route exact path={`${route.path}`} component={route.component} /> </> ) : ( <> <Route exact path={`${route.path}`} component={route.component} /> </> )} </Fragment> ); })} </Switch> </> ); }; export default App;
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