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.
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: