157
rated 0 times
[
163]
[
6]
/ answers: 1 / hits: 7028
/ 4 Years ago, sat, july 25, 2020, 12:00:00
I am developing an ecommerce store having search input and the result is showing as dropdown. Now searching and the search result showing is working. Now I want to close the dropdown on outside click of dropdown. Please check the below code,
const dispatch = useDispatch();
const [toggleSearch, setToggleSearch] = useState(false);
const {trending, searched} = useSelector(state => state.search);
function trendingSearch(e) {
setToggleSearch(true);
dispatch(fetchtrending());
}
function startSearch(e) {
let q = e.target.value;
dispatch(fetchsearch(q));
setToggleSearch(true);
}
<div className="col-12 col-md-6 col-lg-7 mt-3 mb-3 mt-md-0 mb-md-0">
<div className="search-box">
<div className="search-inner">
<input type="text" name="q" placeholder="Search for products, brands and much more" onFocus={(e) => trendingSearch(e)} onChange={(e) => startSearch(e)} />
<button><FontAwesomeIcon icon={faSearch}/></button>
</div>
<div className={toggleSearch ? "search-result" : "search-result d-none"}>
<ul>
{searched !== null && searched.data.length > 0 &&
searched.data.map((search, index) => (
<li key={index}><Link href={"/product/"+search.search_slug+"?pid="+search.search_pid}><a>{search.search_name}</a></Link></li>
))
}
</ul>
</div>
</div>
</div>
I have tried using onBlur
for input
. But the problem is I can't click links inside search result dropdown.
How to achieve closing dropdown only on click outside the the dropdown.
More From » reactjs