Created
November 4, 2023 16:40
-
-
Save ricardovelero/2ddab433f3ab5227970107b0745beb65 to your computer and use it in GitHub Desktop.
Simple React select search example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client'; | |
import React, { useState } from 'react'; | |
import { Input } from '@/components/ui/input'; | |
import { cn } from '@/lib/utils'; | |
import { fetchFilteredPlaces } from '@/lib/data'; | |
export default function SearchDemo() { | |
const [query, setQuery] = useState(''); | |
const [departure, setDeparture] = useState(''); | |
const filteredPlaces = fetchFilteredPlaces(query); | |
const handleClick = (event: React.MouseEvent<HTMLDivElement>) => { | |
// Access the inner text of the clicked div | |
const innerText = event.currentTarget.innerText; | |
setDeparture(innerText); | |
setQuery(''); | |
}; | |
return ( | |
<div className='w-[400px]'> | |
<Input | |
onChange={(event) => setQuery(event.target.value)} | |
type='text' | |
autoFocus | |
id='search' | |
placeholder='Buscar desde donde salir' | |
value={departure} | |
/> | |
<div | |
className={cn('hidden mt-2 border rounded shadow-md', query && 'block')} | |
> | |
{filteredPlaces.length === 0 && query !== '' ? ( | |
<div className='relative cursor-default select-none py-2 px-4 text-gray-700'> | |
Nothing found. | |
</div> | |
) : ( | |
filteredPlaces.map((place) => ( | |
<div | |
key={place.id} | |
className='relative cursor-pointer py-2 px-4 border hover:bg-muted' | |
onClick={handleClick} | |
> | |
{place.name} | |
</div> | |
)) | |
)} | |
</div> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment