I am in the process of developing an application using next js, and I need assistance with designing a search field. The primary functionality I am looking to implement is displaying search suggestions when the user starts typing, but hiding them when the input bar is not in focus.
My challenge arises when trying to show the suggestions again when the user clicks on the input bar. Since the search suggestions contain routes, using onFocus
and onBlur
events becomes tricky as the element loses focus during a click event, and the route only triggers upon release.
Even after attempting CSS solutions, registering the focus out remains elusive. Is there another approach I could try?
Your help would be greatly appreciated!!
Below is a snippet of my code:
const [suggestionState,setSuggestionState] = useState(false);
<input type="input"
ref={inputRef}
autoFocus
className={styles['search-bar-input']}
onFocus={()=>{setSuggestionState(true)}}
onBlur={()=>{setSuggestionState(false)}}
placeholder="Search Bloggo"
onChange={(e)=>{
var trimmedQuery = e.target.value;
trimmedQuery = trimmedQuery.trim();
setSearchQuery(trimmedQuery);
getSuggestions(trimmedQuery)
}}
onKeyDown={(e)=>{handleKeypress(e)}}
/>
{
searchQuery.length == 0 || suggestionState == false? '':
<div className={styles['search-bar-suggestions']}>
<Link>... </Link>
</div>
}