Going back from a redirect tag – React Router

Currently, I created a search bar and I have my search bar linked to my search results like this:

render() {
if (this.props.itemsFetchSuccess) {
  return (
    <Redirect to={{
      pathname: '/search',
      search: `?item-name=${this.props.searchQuery}`
    }} />
  );

as part of the render component of my search bar.

GOOGLE CHROME MAIN -> MAIN LANDING -> SEARCH RESULTS.

But I’m suspecting that because I used a redirect tag in React-Router v4, it’s not adding it to the browser history stack. If I press back on a browser from the search results page, it won’t go back to the page before (i.e. the main landing) but it’ll go back to the page before the main landing.

Is there a better way of doing this as I tried using a Link tag as well but that doesn’t work since it just generates the link and doesn’t actually redirect once the search results are completed.

Thank you!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In your case you can use Redirect with push argument. When press back button it will redirect to previous page correctly.

*push: bool

When true, redirecting will push a new entry onto the history instead of replacing the current one.

<Redirect push to={{
    pathname: '/search',
    search: `?item-name=${this.props.searchQuery}`
}} />

Method 2

Redirect overrides the current entry in history stack and hence you are not able to navigate to the current location on history stack.

See its documentation

You could instead programatically navigate using history.push() in componentWillReceiveProps function.

componentWillReceiveProps(nextProps) {
    if(nextProps.itemsFetchSuccess !== this.props.itemsFetchSucess && nextProps.itemsFetchSuccess) {
         this.props.history.push({
              pathname: '/search',
              search: `?item-name=${nextProps.searchQuery}`
         })
    }
}

P.S. Make sure that the component in which you are using history.push is receiving the Router props, either from the connected component or using withRouter. Check this answer for more details on how to programmatically navigate using React-router

Method 3

Try this:

this.props.history.push(`/search?item-name=${this.props.searchQuery}`);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x