From Switch to Routes (React)

Hey there.

I’m using React to make an app and just found that the Switch component has been updated to Routes component. I had a look at the documentation in order to update my code.

So, my code was like this:


function App() {
  return (
    <Router>
    <div className="app">
      <Switch>
        <Route path="/">
          <Header/> 
          <Home/>
        </Route>
      </Switch>
    </div>
    </Router>
  );
}

Naturally, it did not work as apparently I have react router v6.

I did change my code to this:

function App() {
  return (
    <Router>
    <div className="app">
      <Routes>
        <Route path="/" element={[<Header/>, <Home/>]}>
        </Route>
      </Routes>
    </div>
    </Router>
  );
}

My concern is the following:

In the first option (Switch) you can type anything after the slash, and it works. Example: http://localhost:3000/qwerty

But, when I type the same thing when usng Routes, it does not work.

What am I missing?

In RRv6 all routes by default are exact.
Try adding another route with path="*" (or replace “/” with “*” in your route).

1 Like

Thank you so much. I missed that they were exact.