-
-
Notifications
You must be signed in to change notification settings - Fork 695
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
.
Create a file main.py
in an empty directory and import the necessary modules:
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()
With the .props
builder function you can add html attributes which are in this case interpreted by Quasar to alter the appearance of the input element.
The .classes
builder function can add css classes.
Because NiceGUI comes with TailwindCSS, the w-96
can be used to define the width.
Note that the results
row is cleared in the search function before adding new content.
By adding ui.run()
at the end of the file, and run pyhton3 main.py
While the first version works as expected, we can do better by styling and handling corner cases.
By adding the autofocus
prop the input field is ready for typing after page load.
item-aligned input-class="ml-3"
adjusts the position of the entry field in relation to the border.
The tailwind classes self-center mt-24
are used to position the search bar on the page and transition-all
animates the changes of css events.
search_field = ui.input(on_change=search) \
.props('autofocus outlined rounded item-aligned input-class="ml-3"') \
.classes('w-96 self-center mt-24 transition-all')