Skip to content

Commit

Permalink
fix: add isActive to FormAutosuggest state
Browse files Browse the repository at this point in the history
state.dropDownItems.length > 0 used to determine if an autosuggest component was active or not which was inaccurate. Found an alternative way to specify which component is being interacted with through setting a new bool isActive on the state.
  • Loading branch information
cintnguyen committed Aug 9, 2023
1 parent f5fb6c9 commit 6852ff3
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/Form/FormAutosuggest.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ function FormAutosuggest({
ignoredKeys: ignoredArrowKeysNames,
});
const [isMenuClosed, setIsMenuClosed] = useState(true);
const [isActive, setIsActive] = useState(false);
const [state, setState] = useState({
displayValue: value || '',
errorMessage: '',
Expand Down Expand Up @@ -111,8 +112,10 @@ function FormAutosuggest({
/>
);

const handleClickOutside = (e) => {
if (parentRef.current && !parentRef.current.contains(e.target) && state.dropDownItems.length > 0) {
const handleDocumentClick = (e) => {
if (parentRef.current && !parentRef.current.contains(e.target) && isActive) {
setIsActive(false);

setState(prevState => ({
...prevState,
dropDownItems: [],
Expand All @@ -124,13 +127,12 @@ function FormAutosuggest({
};

const keyDownHandler = e => {
if (e.key === 'Escape') {
if (e.key === 'Escape' && isActive) {
e.preventDefault();

setState(prevState => ({
...prevState,
dropDownItems: [],
errorMessage: !state.displayValue ? errorMessageText : '',
}));

setIsMenuClosed(true);
Expand All @@ -139,10 +141,10 @@ function FormAutosuggest({

useEffect(() => {
document.addEventListener('keydown', keyDownHandler);
document.addEventListener('click', handleClickOutside, true);
document.addEventListener('click', handleDocumentClick, true);

return () => {
document.removeEventListener('click', handleClickOutside, true);
document.removeEventListener('click', handleDocumentClick, true);
document.removeEventListener('keydown', keyDownHandler);
};
});
Expand Down Expand Up @@ -173,6 +175,7 @@ function FormAutosuggest({
};

const handleClick = (e) => {
setIsActive(true);
const dropDownItems = getItems(e.target.value);

if (dropDownItems.length > 1) {
Expand Down Expand Up @@ -204,7 +207,6 @@ function FormAutosuggest({
setState(prevState => ({
...prevState,
dropDownItems: [],
errorMessageText,
}));

setIsMenuClosed(true);
Expand Down

0 comments on commit 6852ff3

Please sign in to comment.