Home > Blockchain >  Push to Login page if user is not logged in, else let inside
Push to Login page if user is not logged in, else let inside

Time:02-12

I want to create a simple Login page that routes me to home page.

In my content page I want the default path to be /, and for login /login. I want to push user to /login route based on a conditional isLoggedIn, at the moment without state manager just for testing purposes. Not sure if I am setting this up correctly, maybe I am doing this completely wrong? I want also to be able to access different routes after being logged in.

function App() {
  const isLoggedIn = true;
  return (
    <Router>
      <Routes>
    <div className="app">
      <Header />
      <div >
        {isLoggedIn
        ? <Route path="/" element={<Content />}></Route>
        : <Route path="/login" element={<Login />}></Route>
      }
      </div>
    </div>
    </Routes>
    </Router>
  );
}

I am getting this error

index.tsx:19 Uncaught Error: [div] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

CodePudding user response:

Well a couple of different factors are at play here.

First of all, the only Route components are allowed as children of the Routes component and so that's the reason you're getting the following error:

index.tsx:19 Uncaught Error: [div] is not a component. All component children of must be a or <React.Fragment>

Next, one way of going about it is to just render a redirect in the element property of the root path if the user is not signed in.

import { Router, Routes, Route, Navigate } from "react-router-dom";

function App() {
  const isLoggedIn = true;
  return (
    <Router>
      <div className="app">
        <Header />
        <div >
          {/*The only children of Routes should be Route components*/}
          <Routes>
            <Route path="/login" element={<Login />} />

            {/* Render a redirect to login if the user is not signed in */}
            <Route
              path="/"
              element={isLoggedIn ? <Content /> : <Navigate to="/login" />}
            />
          </Routes>
        </div>
      </div>
    </Router>
  );
}
  • Related