45 lines
1.2 KiB
TypeScript
45 lines
1.2 KiB
TypeScript
import { useState, useEffect } from 'react'
|
|
import { SearchIcon } from './SearchIcon'
|
|
import { ClearButton } from './ClearButton'
|
|
|
|
interface SearchBarProps {
|
|
value: string
|
|
onChange: (value: string) => void
|
|
placeholder?: string
|
|
}
|
|
|
|
export function SearchBar({ value, onChange, placeholder = 'Search articles...' }: SearchBarProps) {
|
|
const [localValue, setLocalValue] = useState(value)
|
|
|
|
useEffect(() => {
|
|
setLocalValue(value)
|
|
}, [value])
|
|
|
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
const newValue = e.target.value
|
|
setLocalValue(newValue)
|
|
onChange(newValue)
|
|
}
|
|
|
|
const handleClear = () => {
|
|
setLocalValue('')
|
|
onChange('')
|
|
}
|
|
|
|
return (
|
|
<div className="relative">
|
|
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
|
<SearchIcon />
|
|
</div>
|
|
<input
|
|
type="text"
|
|
value={localValue}
|
|
onChange={handleChange}
|
|
placeholder={placeholder}
|
|
className="block w-full pl-10 pr-10 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
|
/>
|
|
{localValue && <ClearButton onClick={handleClear} />}
|
|
</div>
|
|
)
|
|
}
|