Created
October 9, 2023 18:17
-
-
Save HOSS11H/8ddf4451a55742ab229d722c66ac9c26 to your computer and use it in GitHub Desktop.
URL State
This file contains hidden or 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 { MagnifyingGlassIcon } from '@heroicons/react/24/outline'; | |
import { createUrl } from 'lib/utils'; | |
import { useRouter, useSearchParams } from 'next/navigation'; | |
export default function Search() { | |
const router = useRouter(); | |
const searchParams = useSearchParams(); | |
function onSubmit(e: React.FormEvent<HTMLFormElement>) { | |
e.preventDefault(); | |
const val = e.target as HTMLFormElement; | |
const search = val.search as HTMLInputElement; | |
const newParams = new URLSearchParams(searchParams.toString()); | |
if (search.value) { | |
newParams.set('q', search.value); | |
} else { | |
newParams.delete('q'); | |
} | |
router.push(createUrl('/search', newParams)); | |
} | |
return ( | |
<form onSubmit={onSubmit} className="w-max-[550px] relative w-full lg:w-80 xl:w-full"> | |
<input | |
key={searchParams?.get('q')} | |
type="text" | |
name="search" | |
placeholder="Search for products..." | |
autoComplete="off" | |
defaultValue={searchParams?.get('q') || ''} | |
className="w-full rounded-lg border bg-white px-4 py-2 text-sm text-black placeholder:text-neutral-500 dark:border-neutral-800 dark:bg-transparent dark:text-white dark:placeholder:text-neutral-400" | |
/> | |
<div className="absolute right-0 top-0 mr-3 flex h-full items-center"> | |
<MagnifyingGlassIcon className="h-4" /> | |
</div> | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment