React Router DOM error: ‘[Component] is not a Route component’

If you upgraded to React Router DOM v6, or if you are starting with v6 and you’re using code examples from before v6, then you’ll run into breaking changes.

One such breaking change causes the following runtime error:

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

As the error states, starting in v6 you can’t put your component as a child of Route, like this:

<Route path="/"> <Home /> </Route>
Code language: HTML, XML (xml)

Instead, put your component in the element prop, like this:

<Route path="/" element={<Home />} />
Code language: HTML, XML (xml)

Other breaking changes

As mentioned, there are other breaking changes in v6. I suggest reading the official docs about upgrading to v6 if you want to read the details and understand why the changes were made.

I’ll show an example of some of the breaking changes below and how to fix them. First, here’s code that would work before v6:

import { BrowserRouter, Route, Switch } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Switch> <Route exact path="/"> <Home /> </Route> </Switch> </BrowserRouter> ); }
Code language: JavaScript (javascript)

Note: For brevity, this isn’t all of the code, just the parts relevant to the breaking changes.

This code has multiple errors due to breaking changes in v6. Here are the errors and how to fix them:

ErrorFix
Compiler error: ‘Switch’ was not found.Replace ‘Switch’ with ‘Routes’, including in the import.
Compiler error: TS2322: … Property ‘exact’ does not exist.

(You’ll only see this if you’re using TypeScript, but fix it anyway)
Remove ‘exact’ from <Route exact path=”/”>.
Runtime error: [Home] is not a <Route> component…Put the <Home> component in the Route element prop (instead of putting it as a child).

Here’s the code after applying the fixes:

import { BrowserRouter, Route, Routes } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home/>} /> </Routes> </BrowserRouter> ); }
Code language: JavaScript (javascript)

2 thoughts on “React Router DOM error: ‘[Component] is not a Route component’”

Leave a Comment