Search code examples
javascriptreactjsmern

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


I have looked at the previous questions and googled for the answer and I think I almost know what the issue in here is, but don't know how to solve it.

return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        {admin && (
          <>
            <Topbar />
            <div className="container">
              <Sidebar />
              <Route path="/" element={<Home />} />
              <Route path="/users" element={<UserList />} />
              <Route path="/user/:userId" element={<User />} />
              <Route path="/newUser" element={<NewUser />} />
              <Route path="/products" element={<ProductList />} />
              <Route path="/product/:productId" element={<Product />} />
              <Route path="/newproduct" element={<NewProduct />} />
            </div>
          </>
        )}
      </Routes>
    </Router>

Please tell me how to setup the topar and slidebar components here. Requesting my fellow coders to look at this one and thanks in advance.


Solution

  • The error is clear, you only can use the <Route /> tag, and remove the <div className="container"> also. Try this:

        return (
            <>
              <Topbar />
              <Sidebar />
              <Router>
                <Routes>
                  <Route path="/login" element={<Login />} />
                  {admin && (
                      <>  
                        <Route path="/" element={<Home />} />
                        <Route path="/users" element={<UserList />} />
                        <Route path="/user/:userId" element={<User />} />
                        <Route path="/newUser" element={<NewUser />} />
                        <Route path="/products" element={<ProductList />} />
                        <Route path="/product/:productId" element={<Product />} />
                        <Route path="/newproduct" element={<NewProduct />} />
                      </>
                  )}
                </Routes>
              </Router>
            </>
    )
    

    Or you can import your TOPBAR and SIDEBAR components inside every other component.