Home > Software engineering >  route does not work with javascript code in reactjs
route does not work with javascript code in reactjs

Time:02-16

I am trying to make routes for users if my user is available so user can stay at homepage and it is occurring this error (Uncaught Error: [Login] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>)

<BrowserRouter>
  <Routes>
    <Route path="/homepage" element={<Homepage/>}>
      {
        user && user._id
          ? <Homepage/>
          : <Login/>
      }
    </Route>
    <Route path="/login" element={<Login/>}/>
    <Route path="/register" element={<Register/>}/>
  </Routes>
</BrowserRouter>

CodePudding user response:

Homepage and Login need to be rendered as the element of a Route since only Route or React.Fragment components can be children of the Routes component.

<BrowserRouter>
  <Routes>
    <Route
      path="/homepage"
      element={user?._id ? <Homepage/> : <Login/>}
    />
    <Route path="/login" element={<Login/>}/>
    <Route path="/register" element={<Register/>}/>
  </Routes>
</BrowserRouter>

CodePudding user response:

you can try to the way:

<BrowserRouter>
  < Routes>
    <Route path="/homepage" element={user && user.id ? <Homepage /> : <Login />}>
    </Route>
    <Route path="/login" element={<Login />} />
    <Route path="/register" element={<Register />} />
  </Routes>
</BrowserRouter>
  • Related