Scenario:
There is a homepage from where on searching user is redirected to a search page with a query param (eg q=abc). Now being on search page, user again tries to search for a different value so he is again redirected to same search page but with a different query param (eg q=xyz)
Problem:
When I am trying to perform a Redirect from Search page again to the same route with a different query param, I am getting an error "You tried to redirect to the same route you're currently on".
Expected Result:
User should be redirected to the same route again with a different query params so that on pressing back button he can go back to the previous query like it would normally be if it hadn't been a SPA. The result should be similar to the case where I had redirected the user from /search/abc to /search/xyz both using the same component.
Possible Solution:
On submitting a search query, I can check if it is the same route and based on that I can either redirect or update the component state some way. Problem with this solution is that user cannot go back to the previous query on clicking browser's back button. I want the page to be added in history.
Code Snippet:
Using below code for redirection in render function inside Search Component which is present on both homepage and search page
if (this.state.isReady) {
let queryString = "q=" + this.state.q;
return (
<Redirect push to={`/search/hotels?${queryString}`} />
);
}
I think this is a common problem with any site having a search feature so there should be an elegant way to handle such a situation but I am unable to think about it.
Found A Solution:
Instead of using <Redirect />
from React Router, I used history api to push a new route.
this.props.history.push(`/search/hotels?${queryString}`);
I wrapped my SearchComponent inside withRouter which is a HOC provided by React-Router and then used the history api.
Code Snippet:
import { withRouter } from 'react-router-dom';
class SearchComponent {
// Component Code goes here
onSubmit(){
let queryString = "q=" + this.state.q;
this.props.history.push(`/search/hotels?${queryString}`);
}
}
export default withRouter(SearchComponent)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加