DEV Community

Cover image for How to detect a click outside a React component
Morshedul Munna
Morshedul Munna

Posted on

How to detect a click outside a React component

How to detect a click outside a React component

import React, { useEffect, useRef } from 'react';
import { FiSearch } from 'react-icons/fi';
import { useDispatch, useSelector } from 'react-redux';
import { focusToggle } from '../Redux/actionsCreators/searchAction';

const SearchAutoComplete = () => {
    const state = useSelector((state) => state.searchReducer);
    const dispatch = useDispatch();

    const { suggestions, isFocus } = state;

    console.log(isFocus);

    const ref = useRef(null);
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (ref.current && !ref.current.contains(event.target)) {
                dispatch(focusToggle(false));
            }
        };
        document.addEventListener('click', handleClickOutside, true);
        return () => {
            document.removeEventListener('click', handleClickOutside, true);
        };
    }, [dispatch]);

    return (
        <>
            <div className="flex justify-center items-center direction flex-col ">
                <p className="text-[20px] mb-6 font-bold">Search Product</p>
                <div className=" relative ">
                    <div ref={ref} className="flex items-center relative">
                        <FiSearch className=" absolute left-2 text-white-700 " />
                        <input
                            autocomplete="off"
                            onFocus={() => dispatch(focusToggle(true))}
                            className="bg-white-500 py-2 text-[14px] p-[5px] pl-7 min-w-[500px] shadow-boxSad rounded-sm px-6 outline-none"
                            type="text"
                            name="search"
                            placeholder="search..."
                        />
                    </div>
                    <div className=" shadow-boxSad bg-white-100 absolute w-full">
                        {suggestions.map((item, i) =>
                            isFocus ? (
                                <div className="px-7 text-[14px] py-2 bg-white-500 hover:bg-white-100 duration-300 ease-in-out cursor-pointer rounded-sm" key={i}>
                                    {item}
                                </div>
                            ) : null
                        )}
                    </div>
                </div>
            </div>
        </>
    );
};

export default SearchAutoComplete;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)