'React router routes don't match location

Unsure why this isn't working? Everything has been imported correctly so am unsure why I get the following error message in the console:

No routes matched location "/"

App.jsx

import './App.css';
import React from 'react';
import Home from './pages/Home';
import Explore from './pages/Explore';
import { BrowserRouter as Router, Routes, Route, useRoutes} from "react-router-dom";
// import { useState } from "react";

const App = () => {
  let routes = useRoutes([
      <Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="/explore" exact element={<Explore />}/>
      </Routes>
  ])
  return routes;
}

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

export default AppWrapper;

And the Home file

import React from 'react';
import { useNavigate } from "react-router-dom";

const Home = () => {
    const navigate = useNavigate();
    return (
        
        <div>
            <div>
                <button onClick={() => {navigate("/explore");}}>  
                    Explore page
                </button>
                <h1>Home page</h1>
            </div>
        </div>
    );
}

export default Home;


Solution 1:[1]

According to the documentation of useRoutes() from here, you're using the hook in an incorrect manner.

You can use the traditional way of doing routing with react-router-dom, as follows:

const App = () => {
  return (
    <Routes>
      <Route path="/" exact element={<Home />} />
      <Route path="/explore" exact element={<Explore />} />
    </Routes>
  )
}

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

If you really want to use useRoutes, I encourage you to look into the example sent in the link from above.

Solution 2:[2]

The useRoutes hook takes a routes configuration object. Your code is passing JSX. This is an invalid use of the useRoutes hook.

useRoutes

The two methods for rendering routes:

  1. Use the useRoutes hook with routes configuration object.

    const routesConfig = [
      {
        path: "/",
        element: <Home />
      },
      {
        path: "/explore",
        element: <Explore />
      },
    ];
    
    const App = () => {
      const routes = useRoutes(routesConfig);
      return routes;
    };
    
  2. Render the JSX directly.

    const App = () => {
      return (
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/explore" element={<Explore />}/>
        </Routes>
      );
    };
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marius florescu
Solution 2 Drew Reese