This is common purpose, directing unmatch request to notfound page.
making this with react-router v4 looks like previous versions and I expect this sample works below. Links work fine but I expect NotFound component called only unknown url requested; but its always there.
import { BrowserRouter as Router, Route, Link } from 'react-router-dom' class Layout extends Component { render() { return ( <Router> <div className="App"> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/user">User</Link></li> </ul> <Route exact path="/" component={Home}/> <Route path="/user" component={User}/> <Route path="*" component={Notfound}/> </div> </Router> ); } }
its since path="*"
represent all request and notfound component always there but how can I say hide this component for valid url path?
An alternative way to handle 404 page not found in React router is to redirect the user to a different page when they try to go to a page that doesn't exist. Copied! In the example, instead of rendering a PageNotFound component, we redirect the user to / if they go to a route that doesn't exist.
Every Website needs a 404 page if the URL does not exist or the URL might have been changed. To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred.
Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!
React Router's No Match documentation covers this. You need to import the <Switch>
component, then you can remove the path
attribute altogether.
A
<Switch>
renders the first child<Route>
that matches. A<Route>
with no path always matches
This is the example that uses:
<Router> <div> <Switch> <Route path="/" exact component={Home}/> <Redirect from="/old-match" to="/will-match"/> <Route path="/will-match" component={WillMatch}/> <Route component={NoMatch}/> </Switch> </div> </Router>
So in your case, you'd simply drop the path="*"
and introduce the <Switch>
:
<Switch> <Route exact path="/" component={Home}/> <Route path="/user" component={User}/> <Route component={Notfound} /> </Switch>
Remember to include Switch
to your import
statement at the top.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With