reactjs-input-search
Version:
search input with suggestion
83 lines • 2.14 kB
JavaScript
import React, { useEffect, useRef } from 'react';
import useDebounce from '../hooks/useDebounce';
import Suggestion from './Suggestion';
function AutoComplete({
placeholder,
fetchSuggestion,
dataKey,
searchData,
customLoading,
onSelect,
loading,
onFocus,
customStyle,
suggestionShow,
setSuggestionShow,
NoDataFound,
setSearchData,
setLoading,
highlight
}) {
const showSuggestionRef = useRef();
const {
value,
handleChange,
setValue
} = useDebounce(debouncedValue => {
fetchSuggestion(debouncedValue);
}, 500);
const handleApiCall = listName => {
setValue(listName?.[dataKey]);
setSuggestionShow(false);
if (typeof onSelect === 'function') {
onSelect({
key: listName?.[dataKey],
data: listName
});
}
};
const handleClickOutside = e => {
if (showSuggestionRef.current && !showSuggestionRef.current.contains(e.target)) {
setSuggestionShow(false);
}
};
const handleInputChange = e => {
if (!e.target.value) {
setSearchData([]);
}
setLoading(true);
handleChange(e.target.value);
};
useEffect(() => {
document.addEventListener('click', handleClickOutside);
return () => {
document.removeEventListener('click', handleClickOutside);
};
}, []);
return /*#__PURE__*/React.createElement("div", {
className: "inputBox"
}, /*#__PURE__*/React.createElement("span", {
ref: showSuggestionRef
}, /*#__PURE__*/React.createElement("input", {
className: "inputStyle",
placeholder: placeholder,
value: value,
style: customStyle,
onChange: e => handleInputChange(e),
type: "search"
// onSelect={onSelect}
// onBlur={onBlur}
,
onFocus: onFocus
}), value?.length > 0 && suggestionShow && /*#__PURE__*/React.createElement("ul", null, /*#__PURE__*/React.createElement(Suggestion, {
customLoading: customLoading,
loading: loading,
searchData: searchData,
dataKey: dataKey,
handleApiCall: handleApiCall,
inputValue: value,
NoDataFound: NoDataFound,
highlight: highlight
}))));
}
export default AutoComplete;