Home > Back-end >  Routes are not properly updating its just append the previous child route in React
Routes are not properly updating its just append the previous child route in React

Time:10-06

So was trying to set nested routing under one Layout component and I am not unable to navigate properly its just adding up previously visited route Path to the URL while visiting new route path

i have setted up my routes like this :-

<BrowserRouter>
<Routes>
  <Route path='/' element={<Layout Categorie={Categorie} />}> /*Parent Route*/
  <Route path='basket' element={<Basket />}/>
  <Route path='checkout' element={<Checkout />}/>
  <Route path='product/:productId' element={<ProductDetails />}/>
  <Route path='categorie/:categoryId' element={<Categories />}/>
  </Route> /*Parent Route end*/
</Routes>
</BrowserRouter>

I am navigating to two components first is to <Categories /> Component:

<Link to={`categorie/${Categorie.Data[i].id}`}>{Categorie.Data[i].title}</Link>

and second is to <ProductDetails /> component

1 )<Link to={`product/${id}`}>{title}</Link>
2)<CategoryProductActionButton onClick={() => navigate(`product/${id}`) }>view 
   product</CategoryProductActionButton>

now the problem is can successfully navigate to categorie/:categoryId that is http://localhost:3000/categorie/1 url but after that when i visit to my product/:id route I got this http://localhost:3000/categorie/1/product/1 although i was expecting it to be http://localhost:3000/product/1

please help , if there is any feasible solution please suggest

CodePudding user response:

if you have new route and it's not child of current route then you have to pass "/" before any route.

<BrowserRouter>
<Routes>
  <Route path='/' element={<Layout Categorie={Categorie} />}> /*Parent Route*/
  <Route path='/basket' element={<Basket />}/>
  <Route path='/checkout' element={<Checkout />}/>
  <Route path='/product/:productId' element={<ProductDetails />}/>
  <Route path='/categorie/:categoryId' element={<Categories />}/>
  </Route> /*Parent Route end*/
</Routes>
</BrowserRouter>

and you link will be as

<Link to={`/categorie/${Categorie.Data[i].id}`}>{Categorie.Data[i].title}</Link>
  • Related