How to redirect to specific route when first route is matched in react router-dom v6

56 Views Asked by At

In my current application, there's a route like this: "http://localhost:3000/:productId/productInfo". The :productId part is dynamic, meaning it can be anything. Users are redirected to the Product Description page based on the productId.

Requirement: If a user types something like "http://localhost:3000/:productId" directly into the browser and hits enter, I want them to be redirected to the same Product Description page as before, which is available through the route "http://localhost:3000/:productId/productInfo". How can I make this happen using React Router DOM?

userRoutes.jsx

import React from "react";
import { Route, Routes ,Navigate} from "react-router-dom";
import ProductDescription from "./ProductDescription";

const UserRoutes = () => {
  return (
    <Routes>
      <Route path="/:productId/productInfo" element={<ProductDescription />} />

      <Route
        path="/:productId"
        element={<Navigate to="/:productId/productInfo" replace />}
      />
    </Routes>
  );
};

I have read in some article that - I can achieve my requirement with Navigate and replace, but it it not working.

1

There are 1 best solutions below

0
Raphael On

To achieve that, you can use the Navigate component with the replace prop in combination with a function that constructs the target URL. Here's a solution:

import React from "react";
import { Route, Routes, Navigate } from "react-router-dom";
import ProductDescription from "./ProductDescription";

const UserRoutes = () => {
  return (
    <Routes>
      <Route path="/:productId/productInfo" element={<ProductDescription />} />

      <Route
        path="/:productId"
        element={({ params }) => (
          <Navigate
            to={`/${params.productId}/productInfo`}
            replace
          />
        )}
      />
    </Routes>
  );
};

export default UserRoutes;
  1. The element prop of the second Route uses a function instead of a React element.
  2. Inside the function, it uses the Navigate component with the to prop set to the target URL, which is constructed using the params.productId from the route parameters.
  3. The replace prop is used to perform a replacement navigation instead of a push navigation.