javascriptreactjsnext.jsalgoliareact-instantsearch

React InstantSearch- How do you hide "hits" from the screen until the searchBox is used?


I'm using React InstantSearch in Algolia and i'm trying to get it hide its "hits" component by default and only show up when its time to use and click on the searchBox.

I started my research here: https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-display/react/?client=jsx#handling-the-empty-query

I was able to use the query, but couldn't figure out how to apply it to the "hits" component.

So far I have this in my code:

import React from "react";
import Head from 'next/head'
import Header from '../components/Header'
import Hero from '../components/Hero'
import Titles from '../components/Titles'
import CustomHits from "../components/CustomHits";
import { useRouter } from 'next/router'
import Screenfull from "../components/Screenfull"
import { useRef } from "react";
import algoliasearch from "algoliasearch/lite";
import { InstantSearch, SearchBox, Hits, Configure, Pagination, RefinementList, connectStateResults, connectHits, Results } from "react-instantsearch-dom";
    
const searchClient = algoliasearch(
    ("XXXXXXXXXXXX"),
    ("XXXXXXXXXXXXXXX"),
);

const Hit = ({ hit }) => <p>{hit.title}</p>;

export default function Home({ninjas}) {
  const Results = connectStateResults(({ searchState }) =>
    searchState && searchState.query ? (
      <div>Searching for query {searchState.query}</div>
    ) : (
      <div>No query</div>
    )
  );

  return (
    <div>
      <Head>
        <title>Minerva</title>
        <link rel="icon" href="/favicon.ico" />     
      </Head>      
      <Header />
      <Hero />    
      <>
        <InstantSearch 
          searchClient={searchClient} 
          indexName="prod_Directory">  
          {/* Adding Search Box */}        
          <SearchBox/>               
          {/* Adding Data */}
          <Configure  hitsPerPage={2} />
          <RefinementList attribute="title" />
          <Hits  className ="bg-gray-500 z-50" hitComponent={Hit}/>
        <Results />
        </InstantSearch>
      </>  
      <Titles title='SERIES'/>
      <CustomHits />
    </div>
  )
}

Solution

  • You can create a boolean state for "display hits" and set it to true when the search box is focused, and false when it's "blurred".

    const [showHits, setShowHits] = useState(false);
    
    ...
    
    <SearchBox onFocus={()=>setShowHits(true)} onBlur={()=>setShowHits(false)}/>
    
    ...
    
    {showHits ? <Hits hitComponent={Hit} /> : null}
    

    Here's a codesandbox demonstrating this.