Skip to content
Snippets Groups Projects
search-input.tsx 1.46 KiB
"use client"

import { cn } from '@/lib/utils';
import { usePathname, useRouter } from 'next/navigation';
import { useState } from 'react';
import { Icons } from './icons';
import { Button } from './ui/button';
import { Input } from './ui/input';

interface DocsSearchProps extends React.HTMLAttributes<HTMLFormElement> { }

export default function SearchInput({ className, ...props }: DocsSearchProps) {
    const [searchQuery, setSearchQuery] = useState("");
    const router = useRouter();
    const pathname = usePathname();

    function onSearch(event: React.FormEvent) {
        event.preventDefault()

        if (!searchQuery) {
            router.push(pathname)
            return
        }

        const encoededQuery = encodeURIComponent(searchQuery)
        router.push(`${pathname}?search=${encoededQuery}`) // add useSearchParams
    };

    return (
        <form
            onSubmit={onSearch}
            className={cn("relative w-full flex justify-end items-center", className)}
            {...props}
        >
            <Input
                type="search"
                placeholder="Search..."
                className="rounded-full pr-12"
                value={searchQuery}
                onChange={(event) => setSearchQuery(event.target.value)}
            />
            <Button variant="outline" size="lg" className="absolute align-middle h-8 px-2.5 mr-1">
                <Icons.arrowRight className="h-3 w-3" />
            </Button>
        </form>
    );
}