9

I have route defined as below :

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

It works fine. For example localhost:3000/result/cat page works. But when the user decided to remove the :searchTerm from the URL and opens just localhost:3000/result/ it shows empty page. No errors or anything. Just empty page. It is not even hitting my component {Result} too.

So my doubt is how to handle this scenario.? Say I want to redirect the user who tries to open /result/ without :searchTerms to my index page.? How to do that.?

3 Answers 3

25

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.

0
3

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)?

3
  • Tried this. Not working. I mean '/result/cat' also gets redirected to '/'
    – Jithesh Kt
    Commented Dec 6, 2017 at 6:52
  • Updated the answer, should be exact instead of strict Commented Dec 6, 2017 at 6:56
  • 1
    BTW if you're curious, quite a few people think exact should be the default, but it's contentious. Commented Dec 6, 2017 at 7:01
1

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.