Routing in React using React Router v6
In this article, we will teach you how to implement Routing in React using React Router v6 (Version 6). We have already written an article to implement routing in React but it is in the version 5. So today we decided to upgrade the routing example with react-router-dom v6.
Checkout more articles on ReactJS
Demo Application
Here, the output will be the same as compared to v5.
We will recommend you to read the following article:
What’s new in React Router v6
Package Version
Implement routing in React using React Router v6
1. Clone routing application
As we mentioned earlier, we will use the old example which is formed in React Router Version 5. You can check the router version in package.json
.
Refer the following article:
Routing in React JS
2. Upgrade the routing package
Let’s upgrade the react-router-dom
package by running the following command.
1 | npm i react-router-dom |
You will see the version 6 in the package.json
.
3. Update the require changes
1st Change:
You won’t be able to use <Switch>
in the new version, but <Routes>
will be available instead.
1 2 3 4 5 6 7 8 9 10 | import { Routes } from 'react-router-dom'; const routing = ( ... ... <Routes> ... ... </Routes> ) |
2nd Change:
We must now use the element
to load the component instead of the component
, and it is quite simple to send external props to the component directly.
Remove the exact
prop as well, as they are no longer required in the current version.
1 2 3 4 5 6 7 8 9 10 11 | const routing = ( ... ... <Routes> <Route path="/" element={<App />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes > ... ... ) |
4. Output
Let’s put everything together and see how it looks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; import App from './App'; import About from './About'; import Contact from './Contact'; const routing = ( <BrowserRouter> <div> <h3>Clue Mediator</h3> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/contact">Contact</Link> </li> </ul> <Routes> <Route exact path="/" element={<App />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </div> </BrowserRouter> ) ReactDOM.render(routing, document.getElementById('root')); |
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂