Home > Back-end >  How can I replicate the same behavior in react router v6?
How can I replicate the same behavior in react router v6?

Time:07-19

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

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

CodePudding user response:

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

  • Related