diff --git a/src/hooks/use-outside-click.ts b/src/hooks/use-outside-click.ts index 4ac37e3..3fe318b 100644 --- a/src/hooks/use-outside-click.ts +++ b/src/hooks/use-outside-click.ts @@ -3,13 +3,16 @@ import { Dispatch, RefObject, SetStateAction, useEffect } from "react"; const useOutsideClick = ( ref: RefObject, setDropdownVisibility: Dispatch>, - setValue: Dispatch> + setValue: Dispatch>, + clearOnOutsideClick: boolean ) => { useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (ref.current && !ref.current.contains(event.target as Node)) { setDropdownVisibility(false); - setValue(""); + if (clearOnOutsideClick) { + setValue(""); + } } }; diff --git a/src/index.tsx b/src/index.tsx index 4362952..20f6aa8 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -90,6 +90,10 @@ interface IProps { * Clear the input value when any record is selected. */ clearOnSelect?: boolean; + /* + * Clear the input value when an element other than the search box is clicked. + */ + clearOnOutsideClick?: boolean; /* * Icon to be rendered on the left of the input box. */ @@ -121,6 +125,7 @@ const ReactSearchBox: FC = ({ dropdownHoverColor = "#ccc", dropdownBorderColor = "#cacaca96", clearOnSelect = false, + clearOnOutsideClick = false, leftIcon, iconBoxSize = "24px", type = "text", @@ -130,7 +135,12 @@ const ReactSearchBox: FC = ({ const [showDropdown, setDropdownVisibility] = useState(false); const wrapperRef = useRef(null); - useOutsideClick(wrapperRef, setDropdownVisibility, setValue); + useOutsideClick( + wrapperRef, + setDropdownVisibility, + setValue, + clearOnOutsideClick + ); /** * These configs are from Fuse plugin. Check out http://fusejs.io/