Skip to content

Commit

Permalink
fix: add isActive to FormAutosuggest state (#2517)
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 authored Sep 11, 2023
1 parent 67f32e8 commit 4816baa
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 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 @@ -87,6 +88,7 @@ function FormAutosuggest({
};

if (isMenuClosed) {
setIsActive(true);
newState.dropDownItems = getItems(state.displayValue);
newState.errorMessage = '';
}
Expand All @@ -111,8 +113,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 +128,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 +142,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 +176,7 @@ function FormAutosuggest({
};

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

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

setIsMenuClosed(true);
Expand Down

0 comments on commit 4816baa

Please sign in to comment.