From f99e0aba70efad0deb907d8e27f09fc9f527c8a4 Mon Sep 17 00:00:00 2001 From: Rafi Zadanly Date: Fri, 17 Feb 2023 17:07:50 +0700 Subject: Refactor --- src/core/components/elements/NavBar/NavBar.jsx | 31 +++++++++ src/core/components/elements/NavBar/Search.jsx | 89 ++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 src/core/components/elements/NavBar/NavBar.jsx create mode 100644 src/core/components/elements/NavBar/Search.jsx (limited to 'src/core/components/elements/NavBar') diff --git a/src/core/components/elements/NavBar/NavBar.jsx b/src/core/components/elements/NavBar/NavBar.jsx new file mode 100644 index 00000000..212fd341 --- /dev/null +++ b/src/core/components/elements/NavBar/NavBar.jsx @@ -0,0 +1,31 @@ +import Image from "next/image" +import IndoteknikLogo from "@/images/logo.png" +import { Bars3Icon, HeartIcon, ShoppingCartIcon } from "@heroicons/react/24/outline" +import Link from "../Link/Link" +import Search from "./Search" + +const NavBar = () => { + return ( + + ) +} + +export default NavBar \ No newline at end of file diff --git a/src/core/components/elements/NavBar/Search.jsx b/src/core/components/elements/NavBar/Search.jsx new file mode 100644 index 00000000..cca1a97c --- /dev/null +++ b/src/core/components/elements/NavBar/Search.jsx @@ -0,0 +1,89 @@ +import searchSuggestApi from "@/core/api/searchSuggestApi" +import { MagnifyingGlassIcon } from "@heroicons/react/24/outline" +import { useCallback, useEffect, useRef, useState } from "react" +import Link from "../Link/Link" +import { useRouter } from "next/router" + +const Search = () => { + const router = useRouter() + const queryRef = useRef() + const [ query, setQuery ] = useState('') + const [ suggestions, setSuggestions ] = useState([]) + + useEffect(() => { + setQuery(router.query.q) + }, [router.query]) + + const loadSuggestion = useCallback(() => { + if (query && document.activeElement == queryRef.current) { + (async () => { + const dataSuggestion = await searchSuggestApi({ query }) + setSuggestions(dataSuggestion.data.suggestions) + })() + return + } else { + setSuggestions([]) + } + }, [ query ]) + + useEffect(() => { + if (query && document.activeElement == queryRef.current) { + loadSuggestion() + } else { + setSuggestions([]) + } + }, [ loadSuggestion, query ]) + + const handleSubmit = (e) => { + e.preventDefault() + if (query) { + router.push(`/shop/search?q=${query}`) + } else { + queryRef.current.focus() + } + } + + const onInputBlur = () => { + setTimeout(() => { + setSuggestions([]) + }, 100) + } + + return ( +
+ setQuery(e.target.value)} + onBlur={onInputBlur} + onFocus={loadSuggestion} + /> + + + { suggestions.length > 1 && ( + <> +
+ {suggestions.map((suggestion, index) => ( + + {suggestion.term} + + ))} +
+ + ) } +
+ ) +} + +export default Search \ No newline at end of file -- cgit v1.2.3