Home > Software engineering >  React Routing always gives me same Component no matter what
React Routing always gives me same Component no matter what

Time:08-28

So I am making a super simple react app, and I am trying to use routing, But this:

const routing = (
  <Router>
    <React.StrictMode>
      <Routes>
       <Route exact path="/" component={App} />
       <Route exact path="/404" component={<NotFound />} />
      </Routes>
    </React.StrictMode>
  </Router>
)

Does not work, at all. My imports are good, too.

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

yet every time I run it, no matter what URL I go to, it always gives me {App}. Why is this?


The code is in app.js and I am importing it into index.js

CodePudding user response:

So you need to implement like this,

const routing = (
  <Router>
    <React.StrictMode>
      <Routes>
       <Route path="/" element={<App/>} />
       <Route path="*" element={<NotFound />} />
      </Routes>
    </React.StrictMode>
  </Router>
)

CodePudding user response:

I figured that you are using react-router-dom version 6.

You need to provide JSX element like element={<App />} instead of component={App}.

You need -

const routing = (
<React.StrictMode>
  <Router>
      <Routes>
       <Route path="/" element={<App />} />
       <Route path="*" element={<NotFound />} />
      </Routes>
  </Router>
</React.StrictMode>
)

Notice that I haven't used any of exact because react router v6 is able to smartly understand which route element needs to be matched and matches it correctly without using exact.

Read through this migration guide- https://reactrouter.com/en/v6.3.0/upgrading/v5

CodePudding user response:

Since you're using version 6.3.0 of react-router-dom you need to use element instead of component. And exact attribute is not supported in react-router-dom. By default it matches the exact route. To match any not found route use "*" in the route path.

Import BrowserRouter as it is:

import { Route, BrowserRouter, Routes } from "react-router-dom";
const routing = (
<React.StrictMode>
  <BrowserRouter>
      <Routes>
       <Route path="/" element={<App />} />
       <Route path="*" element={<NotFound />} />
      </Routes>
  </BrowserRouter>
</React.StrictMode>
)

Migration guide

  • Related