Categories
React Answers

How to fix the ‘Error “Error: A Route is only ever to be used as the child of element Routes” ‘ error with React Router v6?

Spread the love

Sometimes, we want to fix the ‘Error "Error: A Route is only ever to be used as the child of element Routes" ‘ error with React Router v6.

In this article, we’ll look at how to fix the ‘Error "Error: A Route is only ever to be used as the child of element Routes" ‘ error with React Router v6.

How to fix the ‘Error "Error: A Route is only ever to be used as the child of element Routes" ‘ error with React Router v6?

To fix the ‘Error "Error: A Route is only ever to be used as the child of element Routes" ‘ error with React Router v6, we should put Route components inside the Routes component.

For instance, we write

import { render } from "react-dom";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import App from "./App";
import Expenses from "./routes/expenses";
import Invoices from "./routes/invoices";

const rootElement = document.getElementById("root");
render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="expenses" element={<Expenses />} />
      <Route path="invoices" element={<Invoices />} />
    </Routes>
  </BrowserRouter>,
  rootElement
);

to wrap Routes around the Route components.

Then we can use React Router normally.

Conclusion

To fix the ‘Error "Error: A Route is only ever to be used as the child of element Routes" ‘ error with React Router v6, we should put Route components inside the Routes component.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *