Search code examples
sveltesapper

Search bar Sapper - passing search query between pages


I'm messing around with sapper, and I'm trying to do the following:

enter image description here

As you can see I have a search bar that exists across all the website, what I want to do is, when the user types more than 3 letters, immediately query the server for whatever the user inserted and display the result. The search bar is located in a component SearchBar.svelte that is called in my _layout.svelte.

So for instance, let's say the user is the home page (index.svelte) where he sees a slideshow and a few block texts. When the user types in the search bar, all that would disappear (slideshow,blocktexts,etc) and instead it would display the result of the search (and it would keep updating if the user kept writing more).

I'm not sure how to do that properly with sapper, can anyone point out the proper way to do it? Thanks!

Currently what I'm doing is using the

goto("/search?q="+searchQuery);

In the SearchBar.svelte component, and in the new page (Search.svelte) query the server and display the result, this raises a problem because not only doesn't seem the most elegant solution, but also the input of the search bar loses focus, so if the user kept writing during the page navigation it wouldn't update the query


Solution

  • Instead of the search results being a seperate page, you could add it as an alternative block in _layout.svelte:

    <SearchBox bind:searchTerm />
    
    {#if searchTerm}
      <SearchResults {searchTerm}/>
    {:else}
      <slot></slot>
    {/if}
    

    This way the focus will stay nicely and it's embedded in each page.