Categories
React Answers

How to fix ‘Error: useRoutes() may be used only in the context of a router component’ with React Router v6?

Spread the love

To fix ‘Error: useRoutes() may be used only in the context of a router component’ with React Router v6, we should call useRoutes in the component that’s use to render the route components.

For instance, we write

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useRoutes,
} from "react-router-dom";

const Component1 = () => {
  return <h1>foo</h1>;
};

const Component2 = () => {
  return <h1>bar</h1>;
};

const App = () => {
  const routes = useRoutes([
    { path: "/", element: <Component1 /> },
    { path: "component2", element: <Component2 /> },
    // ...
  ]);
  return routes;
};

const AppWrapper = () => {
  return (
    <Router>
      <App />
    </Router>
  );
};

export default AppWrapper;

to create the App component that calls the useRoutes hook with an array of route items.

Each item has the path that we go to to render the element.

And we render the routes by returning the routes object returned by useRoutes.

And then we put App inside Router to let us use React Router for navigation.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.