Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I replicate the same behavior in react router v6?

when using react router v5, I can get the url and path and passed it to child component

In ParentComponent

const { url, path } = useRouteMatch();

<ChildComponent url={url} path={path} title="child" />

In ChildComponent

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Switch>
  <Route path={url}>
     <div>These will show up</div>
  </Route>
</Switch>

In react router v6, I try to reproduce this behavior but its not working

Parent Component

const { pathname } = useLocation();
<ChildComponent url={pathname} path={pathname} title="child" />

Child Component

<Routes>
      <Route path={url}>
         <div>I want these to show up</div>
      </Route>
</Routes>

>Solution :

In react-router-dom@6 you don’t need to get the url and path from any match object to build nested/descendent routes and links.

In the child component routes are relative to the currently matched route the Routes component is on.

Example:

const ChildComponent = () => (
  <>
    <h2>ChildComponent</h2>
    <Routes>
      <Route
        path="/" // <-- matches/renders on "/test"
        element={<div>I want these to show up</div>}
      />
    </Routes>
  </>
);

const ParentComponent = () => (
  <>
    <h1>ParentComponent</h1>
    <Routes>
      <Route
        path="/" // <-- matches/renders on "/test"
        element={<ChildComponent />}
      />
    </Routes>
  </>
);

function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/test" element={<ParentComponent />} />
      </Routes>
    </div>
  );
}

enter image description here

Edit intelligent-davinci-3bhd0l

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading