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.?
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(); // ... }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With