DEV Community

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

Posted on

3 2

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay