From 64df58da0ec4f36314d0ce1ea68c0668702e4ba6 Mon Sep 17 00:00:00 2001 From: RAGHAV <94848646+raghav1030@users.noreply.github.com> Date: Tue, 3 Oct 2023 19:26:39 +0000 Subject: [PATCH] added '/' as search shortcut --- components/Searchbar/Searchbar.tsx | 5 +++- components/SideNavbar/SideNavbarBody.tsx | 10 ++++---- hooks/useSearchShortcut.tsx | 32 ++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 hooks/useSearchShortcut.tsx diff --git a/components/Searchbar/Searchbar.tsx b/components/Searchbar/Searchbar.tsx index e74fcc447..86b77ef1f 100644 --- a/components/Searchbar/Searchbar.tsx +++ b/components/Searchbar/Searchbar.tsx @@ -1,4 +1,4 @@ -import { useRef, useEffect } from 'react' +import { useRef, useEffect, Ref } from 'react' import SearchIcon from 'assets/icons/SearchIcon' import { SearchbarSuggestions } from './SearchbarSuggestions' @@ -14,6 +14,7 @@ interface SearchbarProps { searchQuery: string showSuggestions: boolean searchQueryIsValid: boolean + inputRef : Ref } const searchOptions = subcategoryArray @@ -24,6 +25,7 @@ export const Searchbar: React.FC = ({ searchQuery, showSuggestions, searchQueryIsValid, + inputRef, }) => { const formRef = useRef(null) const router = useRouter() @@ -88,6 +90,7 @@ export const Searchbar: React.FC = ({ Quick search { const { theme } = useTheme() const [searchState, dispatchSearch] = useSearchReducer() + const inputRef : React.RefObject = useRef(null); + useSearchShortcut({inputRef}) return (
{ )} >
- +
diff --git a/hooks/useSearchShortcut.tsx b/hooks/useSearchShortcut.tsx new file mode 100644 index 000000000..f8e4b60f4 --- /dev/null +++ b/hooks/useSearchShortcut.tsx @@ -0,0 +1,32 @@ +import { useEffect, Ref, RefObject } from "react"; + +interface useSearchShortcutProps { + inputRef : RefObject, +} + +const useSearchShortcut = ({inputRef} : useSearchShortcutProps) => { + useEffect(() => { + const handleSlashKeyPress = (event: KeyboardEvent) => { + // Check if the pressed key is '/' + if (event.key === '/') { + // Prevent the default behavior (e.g., adding '/' to an input field) + event.preventDefault(); + + // Focus the input element + if (inputRef.current) { + inputRef.current.focus(); + } + } + }; + + // Attach the event listener when the component mounts + document.addEventListener('keydown', handleSlashKeyPress); + + // Detach the event listener when the component unmounts + return () => { + document.removeEventListener('keydown', handleSlashKeyPress); + }; + }, [inputRef]); +} + +export default useSearchShortcut \ No newline at end of file