Answer the question
In order to leave comments, you need to log in
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 patch
it doesn't exist.
2) How to render a specific component ONLY if patch
it 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>
);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question