B
B
bzotsss2021-09-21 13:56:43
React
bzotsss, 2021-09-21 13:56:43

Why does the wrong patch always work in React Browser Router?

Hello everyone, I have two questions:
1) Why is the computer always rendered. NotFoundNotFound? According to my idea it should be rendered only if patchit doesn't exist.
2) How to render a specific component ONLY if patchit doesn't exist anywhere? Google found patch="*"it, but for some reason this option doesn’t work for me :(. Below is the code.

import "./styles.css";
import TestComponent from "./TestComp";
import TestComponent2 from "./TestComp2";
import { Link, Route, BrowserRouter, Switch } from "react-router-dom";
const NotFound = () => {
  return <div>Not Found</div>;
};
export default function App() {
  return (
    <BrowserRouter>
      <Switch>
        <div className="App">
          <Link to="/test/1">Link</Link>
          <Link to="/test/2">Link2</Link>
          <Route path="*" exact component={NotFound} />
          <Route path="/test/1" exact component={TestComponent} />
          <Route path="/test/2" component={TestComponent2} />
        </div>
      </Switch>
    </BrowserRouter>
  );
}

And a link to the sandbox https://codesandbox.io/s/dreamy-zhukovsky-r0nt4?fi... . Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2021-09-21
@bzotsss

Inside the Switch, the first route found is fired. Put NotFound last.
https://reactrouter.com/web/api/Switch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question