Home > front end >  Waht's the reason routing in my project not works correctly?
Waht's the reason routing in my project not works correctly?

Time:06-23

When I type /create after the address, I expect It shows Home component. Since I don't use from exact prop. Because path='/c' matches with /create. But it shows Create component. It first worked fine and when I used from exact prop it worked fine as expects. But I don't know why it not works as expects after I removed exact from the first Route.

It works fine only if I do: <Route path="/" element={<Home />} />

Note: I used this for run server: npx json-server --watch data/db.json --port 8000

See that on Codesandbox: https://codesandbox.io/s/epic-feather-uz2iur

It's the section of my Routes:

function App() {
  return (
    <Router>
      <div className="App">
        <Navbar />
        <div className="content">
          <Routes>
            <Route path="/c" element={<Home />} />
            <Route path="/create" element={<Create />} />
          </Routes>
        </div>
      </div>
    </Router>
  );
}

It gives the same result on my Webstorm(react-router-dom version 5):

  <Router>
      <div className="App">
          <Navbar />
          <div className="content">
              <Switch>
                  <Route path="/">
                      <Home />
                  </Route>
                  <Route path="/create">
                      <Create />
                  </Route>
              </Switch>
          </div>
      </div>
  </Router>

CodePudding user response:

Using react-router-dom version 5 you can use Switch along with * and it should work

<Router>
  <div className="App">
    <Navbar />
    <div className="content"></div>
    <Switch>
      <Route path="/c*">
        <Home />
      </Route>
      <Route path="/create">
        <Create />
      </Route>
    </Switch>
  </div>
</Router>

According to documentation

A Switch looks through all its children elements and renders the first one whose path matches the current URL. Use a any time you have multiple routes, but you want only one of them to render at a time

Working example

CodePudding user response:

There was a breaking change in v6 regarding "exact" prop - it does not exist anymore and all paths are by default exact.

You can read more here: upgrading to v6

Route exact is gone. Instead, routes with descendant routes (defined in other components) use a trailing * in their path to indicate they match deeply

  • Related