-
-
Notifications
You must be signed in to change notification settings - Fork 594
Search as You Type
In this a step-by-step tutorial, we'll learn how to create a "search as you type" cocktail lookup using NiceGUI. The website will allow users to type in the name of a cocktail, and as they type, it will display matching cocktails with their images. The full example can be fetched from the repository.
- Have Python 3.8 or greater installed.
- Install NiceGUI with
pip install nicegui
.
import asyncio
from typing import Optional
import httpx
from nicegui import events, ui
We'll be using httpx to make asynchronous HTTP requests to the cocktail database. Read more about why async is crucial in our FAQ.
api = httpx.AsyncClient()
Let's first create a simple version of the search function, without handling edge cases or optimizing the user experience.
async def search(e: events.ValueChangeEventArguments) -> None:
'''Search for cocktails as you type.'''
response = await api.get(f'https://www.thecocktaildb.com/api/json/v1/1/search.php?s={e.value}')
results.clear()
with results: # enter the context of the the results row
for drink in response.json()['drinks'] or []: # iterate over the response data of the api
with ui.image(drink['strDrinkThumb']).classes('w-64'):
ui.label(drink['strDrink']).classes('absolute-bottom text-subtitle2 text-center')
The user interface is quite simple: a search field and a horizontal row which automatically breaks if there are too many results.
search_field = ui.input(on_change=search).props('outlined rounded).classes('w-96')
results = ui.row()
Note that the results
row is cleared in the search function before adding new content.