Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 738
Jithesh Kt Avatar asked Dec 06 '17 06:12

Jithesh Kt


People also ask

How do you pass parameters in react router dom route?

To pass parameters to component with React Router, we can use the useParams hook. <Route path="/details/:id" component={DetailsPage} />; to add the id parameter to our route. import { useParams } from 'react-router'; export default function DetailsPage() { const { id } = useParams(); // ... }

How do you handle URL parameters in react?

Using React Router, when you want to create a Route that uses a URL parameter, you do so by including a : in front of the value you pass to Route 's path prop. Finally, to access the value of the URL parameter from inside of the component that is rendered by React Router, you can use React Router's useParams Hook.

How do I get the full URL in react dom router?

Use the window object to get the current URL in React, e.g. window. location. href returns a string containing the whole URL. If you need to access the path, use window.

How do I use react router without changing URL?

To use React Router without changing the URL, we can use the MemoryRouter component. to import the MemoryRouter component and then wrap it around App to let us navigate with React Router without changing URLs.


1 Answers

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.

like image 89
Rich Churcher Avatar answered Oct 12 '22 14:10

Rich Churcher