Home > database >  Why do I have an error "[Header] is not a <Route> component."?
Why do I have an error "[Header] is not a <Route> component."?

Time:05-20

I have a social media app and my App.js looks like this:

<div className="App">
      <Router>
        {!name ? (
          <>
            
            <Login />
          </>
        ) : (
          <Routes>
            <Route exact path="/">
              <Header />
              <Feed />
              <Model />
            </Route>
            <Route exact path="">
              <Navigate to="/" />
            </Route>
          </Routes>
        )}
      </Router>
    </div>

So if user is authorized it redirects us to the main page but if they're unauthorized, we have a Login page.

But I have the next error in console:

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

What causes this error?

CodePudding user response:

In version 6 of react-router, you're expected to use the element prop to tell it what to render:

<Route path="/" element={(
  <>
    <Header />
    <Feed />
    <Model />
  </>
)}/>

Adding children to a route is reserved for defining nested routes, as in:

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="users" element={<Users />}>
    <Route path="/" element={<UsersIndex />} />
    <Route path=":id" element={<UserProfile />} />
  </Route>
</Routes>

CodePudding user response:

If you are using an older version of react-router-dom:

<Route exact path="/" component={(
    <React.Fragment>
          <Header />
          <Feed />
          <Model />
    </React.Fragment>
)} />

If you are using V6, replace the name of the component prop with element and that will do it.

As of V6, all children of Route or Routes MUST be a Route. If you have for example a route with path="/home" and you have route /home/abc then the route/abc should go inside of the /home route as a child to its Route component.

Doesn't fully make sense to me why they chose this way of doing this, but hey, the community doesn't matter, right? :)

  • Related