Sibling route is not being replaced but appended to the previous url react router v6

Viewed 25

I've been implementing a nested route feature in react using react-router v6. When I go to the next sibling route it's just adding it to the previous sibling for example I want that when I go to "sibling 1" it should show url/home/sibling1 and then if I want to go to "sibling 2" it should route to url/home/sibling2 which is not the case, it's just appending sibling 2 to 1 like this "url/home/sibling1/sibling2".

Here is my route file:-

function App() {
  return (
    <BrowserRouter> 
      <Routes>
        <Route path='/home' element={<Home />} >
          <Route path='sibling1' element={<Sibling1 />} />
          <Route path='sibling2' element={<Sibling2 />} />
          <Route path='sibling3' element={<Sibling3 />} />
        </Route>
        <Route path="*" element={<Page404 />} />
      </Routes>
    </BrowserRouter>
  );
}

and here is how I am navigating from sibling 1 to sibling 2:-

<div className='btn'>
  <Link to="sibling2">
    <button>
      sibling2
    </button>
  </Link>
</div>
1 Answers

To navigate to a sibling route from one of the other sibling components you will want to navigate relative to the parent Routes component. Prepend the target path with "..". ".." removes one path segment, i.e. from "/home/sibling1" to "/home", then navigates relatively to result path "/home/sibling2".

Example:

<Link to="../sibling2">
  <button>
    sibling2
  </button>
</Link>

Edit sibling-route-is-not-being-replaced-but-appended-to-the-previous-url-react-route

Related