Steps to implement React Router v6
Step 1: Create React app
npx create-react-app router6
Step 2: Install React Router v6
npm install react-router-dom@next
Updated Dependencies in package.json File:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.0.0-beta.0"
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Project Structure:
Example:
// Filename - App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import { useNavigate, useParams, useLocation, useMatch } from 'react-router-dom';
function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/profile/john">Profile</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/profile/:username" element={<Profile />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
);
}
function Home() {
return <h1>Welcome to the Home Page!</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function Profile() {
const { username } = useParams();
const location = useLocation();
const navigate = useNavigate();
const matchAbout = useMatch('/about');
const handleButtonClick = () => {
navigate('/');
};
return (
<div>
<h1>User Profile: {username}</h1>
<p>Current URL: {location.pathname}</p>
<button onClick={handleButtonClick}>Go to Home</button>
{matchAbout && <p>This is the About page!</p>}
</div>
);
}
function NotFound() {
return <h1>404 - Not Found</h1>;
}
export default App;
Steps to run the application: Use the below command in the terminal.
npm start
Output:
Migrate to React Router v6
React Router v6 brings significant changes and improvements over its predecessor, offering a more intuitive API and better performance. Migrating to React Router v6 might seem daunting, but with proper guidance, the transition can be smooth and beneficial for your React applications.
Contact Us