In this tutorial, we will see how to fix the Error: useRoutes() may be used only in the context of a
I was recently using the react-router-dom v6 library in the new project and was getting this error.
After a quick debugging, I found that the error was because now the routes have to be wrapped under BrowserRouter.
For example, suppose this is your App.jsx.
// App.jsx
import * as React from "react";
import { Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import FAQ from "./components/FAQ";
const App = () => {
return (
<Routes>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="faq" element={<FAQ />} />
</Routes>
);
};
export default App;
Then this App component has to be wrapped inside BrowserRoute to make it work.
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import reportWebVitals from "./reportWebVitals";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();