react router v4 default page(not found page)

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.


Although the accept solution does provide the answer, but it wouldn't work when you have nested Routes

For instance, if the Home component has nested Routes like /home, /dashboard and if the visited url is /db, it would show a NotFound component only within the Route section, but not the page as a whole.

To avoid this, you can go along with a very simple tweak of using a component and a Provider

const NoMatch = (props) => (
    <Redirect to={{state: {noMatch: true}}} />
)

const ProviderHOC = (NotFoundRoute) => {
    const RouteProvider = (props) => {
        if(props.location && props.location.state && props.location.noMatch) {
           return  <NotFoundRoute {...props} />
        }
        return props.children;
    }
    return withRouter(RouteProvider)

}

export default ProviderHOC;

And then you can use it like

const RouteManager  = ProviderHOC(NotFoundComponent);

<Router>
  <RouteManager>
    <Switch>
      <Route path="/" exact component={Home}/>
      <Redirect from="/old-match" to="/will-match"/>
      <Route path="/will-match" component={WillMatch}/>
      <NoMatch />
    </Switch>
  </RouteManager>
</Router>

and within Home component

render() {
    return (
         <Switch>
               <Route path="/home" component={NewHome} />
               <Route path="/dashboard" component={Dashboard} />
               <NoMatch />
         </Switch>
    )
}