Open In App

Migrate to React Router v6

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Enhancements in React Router v6

React Router v6 introduces several key enhancements and changes that greatly improve the routing experience in React applications. Here’s a deeper dive into the improvements:

  • Simplified API: React Router v6 streamlines the API, making it more intuitive and easier to understand.
  • Improved Nesting: With v6, nesting routes become more straightforward and flexible.
  • Hooks-based Navigation: React Router v6 embraces React’s hook-based architecture by introducing hooks for navigation.
  • Dynamic Route Parameters: Handling dynamic route parameters is made simpler with the `useParams` hook.
  • Enhanced Performance: The new architecture ensures efficient navigation and minimal overhead, contributing to a smoother user experience, especially in large-scale applications.
  • TypeScript Support: React Router v6 offers improved TypeScript support, with enhanced type definitions and better integration with TypeScript projects.

Install React Router v6

npm install react-router-dom@next

Features

Using the <Routes> Component for Routing:

The <Routes> component is the new way to define routes in React Router v6. It replaces the combination of <Switch> and <Route> components used in previous versions.

 <Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>

Leveraging the useNavigate Hook for Navigation:

The useNavigate hook provides a programmatic way to navigate between routes without using <Link> components.

 const navigate = useNavigate();

Adopting the useParams Hook for Accessing Route Parameters:

The useParams hook allows you to access route parameters directly in functional components.

const { username } = useParams();

Employing the useLocation Hook for Accessing the Current Location

The useLocation hook enables components to access information about the current URL, such as pathname and search parameters.

const location = useLocation();

Utilizing the useMatch Hook for Matching Routes:

The useMatch hook allows you to check if the current location matches a specific route pattern.

const match = useMatch('/about');

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:

Screenshot-2024-04-25-112847

project structure

Example:

JavaScript
// 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:

Recording-2024-04-25-113034-(1)

output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads