DEV Community

David Babalola
David Babalola

Posted on • Updated on

Moving to React-Router-Dom v6 from v5 or earlier

Earlier today I was following a tutorial on React (I am quite new to React) that was made earlier in 2021. When I installed React Router and added it, I noticed that I was getting this error:

Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

After researching online, I found out that the tutorial was made with React-Router-Dom v5 and the version I installed was version 6.

After a few hours of researching and debugging , I was able to get everything to work.

Your original code may look something like the following:

import React from 'react';
import { Container } from 'react-bootstrap';
import { BrowserRouter as Router, Route} from 'react-router-dom'
import Footer from './components/Footer';
import Header from './components/Header'
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';

function App() {
  return (
    <Router>
      <Header />
      <main className='py-3'>
        <Container>
          <Route path='/' component={HomeScreen} exact />
          <Route path='/product:id' component={ProductScreen} />
        </Container>
      </main>
      <Footer />
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

However, in the new version of React Router, you need to wrap all the <Route /> components in a <Routes /> component (it replaces the <Switch />component).

For the Route component, it will be changed from
<Route path='/' component={HomeScreen} exact/>
<Route path='/product:id' component={ProductScreen} />

to

<Route path='/' element={<HomeScreen />} />
<Route path='product/:id' element={<ProductScreen />} />

See how the preceding forward slash in the second statement has been removed and that the colon (":") is preceded by a forward slash. Furthermore, you have element instead of component, and instead of just typing the name of the component the route is pointing to, you write it as if you are rendering it (like <ProductScreen />).
Another thing to note is that you don't need the exact property again because Route paths match exactly by default.

Also, if you want to access the parameters in the URL, you will have to import useParams from 'react-router-dom'

Thats all for now! Hope you enjoyed reading this.

To learn more about this, click here or here.

Top comments (0)