skip to Main Content

In my React typescript application I am using React Router to navigate through the App. The workflow is as follows:

  1. User types in a search term in a textfield and hits "Search"
  2. User gets directed to /search-result?searchterm=abcde and see’s the results that fit this search term
  3. User clicks on one result and lands on the corresponding profile page e.g. /{user-id}/overview

The user can now navigate for example to the contacts of a user, the path then changes to /{user-id}/contacts

Problem is: I have a breadcrumb on the top of the page (search / search-result / {username}) and when the user clicks on ‘search-result’ in this breadcrumb, I want to navigate back to the search result. But I can’t just do

navigate(-1)

Because the user may has navigated to other urls like /{user-id}/contacts

Can I somehow search inside the history stack to find the URL that contains ‘/search-result?searchterm=abcde’ and navigate back to it?

Or should I change the pattern of my urls?

2

Answers


  1. I would advise you to redirect to the specific url /search-result when the user clicks on ‘search-result’ in the breadcrumb. In this way even you change the way the routing is working that link will always redirect to the correct page.

    const handleSearchClick = () => navigate("/search-result");
    
    Login or Signup to reply.
  2. Here are the steps I would follow:

    • Tweak the SearchResult component to check if the searchterm query parameter is empty.
      • If it is empty, load the Search component instead, by redirecting to /search route.
      • If it has some value, do what you are currently doing.
    // Here I assume you are using react-router
    export default function SearchResult() {
      const [searchParams, setSearchParams] = useSearchParams();
      const searchTerm = searchParams.get("searchterm");
    
      if (!searchTerm) navigate("/search");
    
      return <>Results containing Search Term</>
    }
    

    Now, whenever the user clicks on search-result link in the breadcrumb (search / search-result / {username}), redirect them to /search-result route which won’t have any searchterm query parameter. But due to the tweaks in SearchResult component, the user would eventually get redirected to /search route.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search