Skip to content

Instantly share code, notes, and snippets.

@ricardovelero
Created November 4, 2023 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardovelero/2ddab433f3ab5227970107b0745beb65 to your computer and use it in GitHub Desktop.
Save ricardovelero/2ddab433f3ab5227970107b0745beb65 to your computer and use it in GitHub Desktop.
Simple React select search example
'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