Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: outside click prop; change default behavior #184

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/hooks/use-outside-click.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import { Dispatch, RefObject, SetStateAction, useEffect } from "react";
const useOutsideClick = (
ref: RefObject<HTMLDivElement>,
setDropdownVisibility: Dispatch<SetStateAction<boolean>>,
setValue: Dispatch<SetStateAction<string>>
setValue: Dispatch<SetStateAction<string>>,
clearOnOutsideClick: boolean
) => {
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
setDropdownVisibility(false);
setValue("");
if (clearOnOutsideClick) {
setValue("");
}
}
};

Expand Down
12 changes: 11 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -121,6 +125,7 @@ const ReactSearchBox: FC<IProps> = ({
dropdownHoverColor = "#ccc",
dropdownBorderColor = "#cacaca96",
clearOnSelect = false,
clearOnOutsideClick = false,
leftIcon,
iconBoxSize = "24px",
type = "text",
Expand All @@ -130,7 +135,12 @@ const ReactSearchBox: FC<IProps> = ({
const [showDropdown, setDropdownVisibility] = useState<boolean>(false);
const wrapperRef = useRef<HTMLDivElement>(null);

useOutsideClick(wrapperRef, setDropdownVisibility, setValue);
useOutsideClick(
wrapperRef,
setDropdownVisibility,
setValue,
clearOnOutsideClick
);

/**
* These configs are from Fuse plugin. Check out http://fusejs.io/
Expand Down