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 77baba9
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 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);

Check failure on line 35 in src/Form/FormAutosuggest.jsx

View workflow job for this annotation

GitHub Actions / tests

Trailing spaces not allowed
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 : '',
dropDownItems: [],

Check failure on line 135 in src/Form/FormAutosuggest.jsx

View workflow job for this annotation

GitHub Actions / tests

Trailing spaces not allowed
}));

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 77baba9

Please sign in to comment.