Add "x" button to cancel search in search bar (#107)

This commit is contained in:
Stefan Hynst
2024-05-30 03:26:04 +02:00
committed by GitHub
parent 1cd2b273f9
commit 833237b613
2 changed files with 29 additions and 13 deletions

View File

@@ -94,7 +94,7 @@ export function ExpenseList({
const groupedExpensesByDate = getGroupedExpensesByDate(expenses) const groupedExpensesByDate = getGroupedExpensesByDate(expenses)
return expenses.length > 0 ? ( return expenses.length > 0 ? (
<> <>
<SearchBar onChange={(e) => setSearchText(e.target.value)} /> <SearchBar onValueChange={(value) => setSearchText(value)} />
{Object.values(EXPENSE_GROUPS).map((expenseGroup: string) => { {Object.values(EXPENSE_GROUPS).map((expenseGroup: string) => {
let groupExpenses = groupedExpensesByDate[expenseGroup] let groupExpenses = groupedExpensesByDate[expenseGroup]
if (!groupExpenses) return null if (!groupExpenses) return null

View File

@@ -1,33 +1,49 @@
import * as React from "react" import * as React from 'react'
import {Input} from "@/components/ui/input"; import { Input } from '@/components/ui/input'
import {cn} from "@/lib/utils"; import { cn } from '@/lib/utils'
import { import { Search, XCircle } from 'lucide-react'
Search
} from 'lucide-react'
export interface InputProps export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {} extends React.InputHTMLAttributes<HTMLInputElement> {
onValueChange?: (value: string) => void
}
const SearchBar = React.forwardRef<HTMLInputElement, InputProps>( const SearchBar = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => { ({ className, type, onValueChange, ...props }, ref) => {
const [value, _setValue] = React.useState('')
const setValue = (v: string) => {
_setValue(v)
onValueChange && onValueChange(v)
}
return ( return (
<div className="mx-4 sm:mx-6 flex relative"> <div className="mx-4 sm:mx-6 flex relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input <Input
type={type} type={type}
className={cn( className={cn(
"pl-10 text-sm focus:text-base bg-muted border-none text-muted-foreground", 'pl-10 text-sm focus:text-base bg-muted border-none text-muted-foreground',
className className,
)} )}
ref={ref} ref={ref}
placeholder="Search for an expense…" placeholder="Search for an expense…"
value={value}
onChange={(e) => setValue(e.target.value)}
{...props} {...props}
/> />
<XCircle
className={cn(
'absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 cursor-pointer',
!value && 'hidden',
)}
onClick={() => setValue('')}
/>
</div> </div>
) )
} },
) )
SearchBar.displayName = "SearchBar" SearchBar.displayName = 'SearchBar'
export { SearchBar } export { SearchBar }