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?
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.
this is my solution with two components.
const NotFound = () => <div>Not found</div>
const NotFoundRedirect = () => <Redirect to='/not-found' />
//root component
<Switch>
<Route path='/users' component={UsersPages} />
<Route path='/not-found' component={NotFound} />
<Route component={NotFoundRedirect} />
</Switch>
//UsersPages component
<Switch>
<Route path='/home' component={HomePage} />
<Route path='/profile' component={ProfilePage} />
<Route component={NotFoundRedirect} />
</Switch>
That work perfect for me. Thanks.
This method works perfectly, it allows to make a redirect if the url does not exist or if it is false
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/sorties-scolaires" component={SortiesScolaires} />
<Route path="/voyages-entreprise" component={VoyagesEntreprise} />
<Route path="*">
<Redirect to="/" />
</Route>
</Switch>
</Router>
);
}