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

Router 6.4: useHref() may be used only in the context of a <Router> component

This is not duplicate of this because the answers there don’t address how to do this with router 6.4 (namely with createBrowserRouter and createRoutesFromElements).
Also not sure if component layout is similar.


This is my code:

const router = createBrowserRouter(
  createRoutesFromElements(
    <React.Fragment>
      <Route path="/" element={<Test />} />
      <Route path="dashboard" element={<Test2 />} />
    </React.Fragment>
  )
);

const { Header, Content, Sider } = Layout;
function App() {
  return (
    <Layout style={{ height: "100%" }}>
      <Header className="header">
        <Menu theme="dark" mode="horizontal" defaultSelectedKeys={["2"]} items={items1} />
      </Header>
      <Layout>
        <Content
          style={{
            padding: 24,
            margin: 0,
            minHeight: 280,
          }}
        >
          <RouterProvider router={router} />
        </Content>
      </Layout>
    </Layout>
  );
}

I am getting error

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

useHref() may be used only in the context of a component

I understand this is related to my Links not embedded within Router, but using this new API of 6.4 react router how do I solve this problem?

>Solution :

Even with the new RRDv6.4 Data APIs and Data Routers, the Link components still need to be rendered within the routing context. You can move all the App component layout to be a layout route configured when you create the router.

Example:

const { Header, Content, Sider } = Layout;

const AppLayout = () => (
  <Layout style={{ height: "100%" }}>
    <Header className="header">
      <Menu
        theme="dark"
        mode="horizontal"
        defaultSelectedKeys={["2"]}
        items={items1}
      />
    </Header>
    <Layout>
      <Content
        style={{
          padding: 24,
          margin: 0,
          minHeight: 280,
        }}
      >
        <Outlet />
      </Content>
    </Layout>
  </Layout>
);

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route element={<AppLayout />}>
      <Route path="/" element={<Test />} />
      <Route path="dashboard" element={<Test2 />} />
    </Route>
  )
);

function App() {
  return (
    <RouterProvider router={router} />
  );
}
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