How to handle empty URL parameter in react router dom (4.xx)

I believe you can just add a question mark for an optional parameter, so:

<Route path='/result/:searchTerm?' component={Result} />

This works because React Router 4 uses path-to-regexp to interpret its path property.

To answer the last part of your question, you could simply test the value of :searchTerm and if it was undefined, redirect the user.


Switch is a component used to render routes exclusively. So, in general, at the end of children inside Switch, you can provide a default route (in your case the index page) for any path that you don't explicitly specify in other routes.

Eg:

        <Switch>
          <Route exact path='/'
            component={()=>(<Redirect to='/index'/>)}/>
          <Route exact path='/index' component={Index}/>
          <Route path='/result/:searchTerm' component={Result}/>
          .
          .
          // default route, gets rendered if none of the above match:
          <Route component={NotFound404}/>
        </Switch>

If you want to redirect the user to another page if the param is not added, you would do the following

<Switch>
   <Redirect from='/result/' to='/' exact />
   <Route path='/result/:searchTerm' component={Result}/>
</Switch>

However if you wish to show the same page then without the params too, you could just use optional path params. Check this answer for more details: How to make path param to be optional in react router dom(v4)?