user393031
user393031

Reputation: 25

React Error - No routes matched location "/"

I have a problem with routing in React, using this code i receive warning "No routes matched location "/". Can anyone help me?

{isLogged ?
        <div className={'app-wrapper d-flex'}>
            <NavbarContainer/>
            <div className={`content-wrapper`}>
                <Routes>
                    <Route path={'/'}
                           element={<Employees/>}/>
                    {isLogged && user.roles.includes('Admin' || 'ADMIN') ?
                        <Route path={'add-employees'} element={<AddEmployeeContainer/>}/>
                        : null}
                </Routes>
            </div>
        </div> : <>
            <Routes>
                <Route path={'login'}
                       element={<LoginContainer/>}/>
                <Route path={'registration'} element={<RegistrationContainer/>}/>
            </Routes>
        </>
 }

Upvotes: 1

Views: 3663

Answers (2)

Drew Reese
Drew Reese

Reputation: 202686

You are missing a route on path "/" when isLogged is false.

Instead of conditionally rendering one set of routes or another, just render all of your routes and implement auth redirection.

const AdminLayout = ({ isLogged, user }) => 
  isLogged && user.roles.includes('Admin' || 'ADMIN')
    ? <Outlet />
    : <Navigate to="/login" replace />;

...

<div className={'app-wrapper d-flex'}>
  <NavbarContainer/>
  <div className={`content-wrapper`}>
    <Routes>
      <Route element={<AdminLayout isLogged={isLogged} user={user} />}>
        <Route path={'/add-employees'} element={<AddEmployeeContainer />} />
      </Route>
      <Route path="/" element={<Employees/>} />
      <Route path="/login" element={<LoginContainer />} />
      <Route path="/registration" element={<RegistrationContainer />} />
    </Routes>
  </div>
</div>

Upvotes: 2

Evren
Evren

Reputation: 4410

You should replace path={'/'} with this one path="/"

Upvotes: 1

Related Questions