React Dropdown Issue: All Dropdowns Open Simultaneously When Clicking Any Dropdown Button or External Elements

I am building a reusable dropdown component in React that can be toggled both by clicking its button and by clicking on external elements (watchElements). The dropdown works fine individually, but when I render multiple instances of the dropdown, clicking any button or external element toggles all dropdowns at once.

I want each dropdown instance to manage its own state independently so that clicking on a specific button or external element toggles only that specific dropdown.

Here is the current code for the Dropdown component:

import React, { useState, useEffect, useRef } from "react";

mport Button from "./Button";
import { RiArrowDownCircleFill } from "@remixicon/react";
import { constants } from "../constants";

const Dropdown = ({
  content,
  img = {
    url: "",
    alt: ""
  },
  img_classes = "",
  btn_classes = "",
  className = "text-center",
  content_wrapper_classes = "",
  btn_child = (
    <RiArrowDownCircleFill
      size={constants.static_sytles.icon_size_sm}
      className="text-white animate-bounce"
    />
  ),
  children,
  watchElements = []
}) => {
  const [isOpen, setIsOpen] = useState(false); 
  const dropdownRef = useRef(null);

  const toggleDropdown = (event) => {
    // console.log(dropdownRef.current)
    console.log('here is the event', event.target)
    console.log(dropdownRef.current.contains(event.target))
    if (dropdownRef.current && dropdownRef.current.contains(event.target)) {
      setIsOpen((prev) => !prev);
    }
  };

  const closeDropdown = () => {
    setIsOpen(false);
  };

  const handleClickOutside = (event) => {
    if (
      dropdownRef.current &&
      !dropdownRef.current.contains(event.target) &&
      !watchElements.some(
        (el) => el && el.contains && el.contains(event.target)
      )
    ) {
      closeDropdown();
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);

    if (watchElements.length) {
      watchElements.forEach((watchElement) => {
        if (watchElement) {
          watchElement.addEventListener("click", toggleDropdown);
        }
      });
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);

      if (watchElements.length) {
        watchElements.forEach((watchElement) => {
          if (watchElement) {
            watchElement.removeEventListener("click", toggleDropdown);
          }
        });
      }
    };
  }, [watchElements]);

  return (
    <div className={`${className}`}>
      <Button
        className={`${btn_classes} mt-3 flex items-center justify-center w-full`}
        // onClick={toggleDropdown}
        isDefault={false}
      >
        {btn_child}
      </Button>

      {/* Dropdown Menu */}
      <div
       ref={dropdownRef}
        className={` ${content_wrapper_classes} right-0 top-full w-full bg-white ring-opacity-5 overflow-hidden transition-all duration-700 ease-in-out ${
          isOpen  ?  "max-h-screen animate-flip-down" : "max-h-0"
        }`}
      >
        {img.url && (
          <img className={`${img_classes}`} src={img.url} alt={img.alt} />
        )}
        {children}
      </div>
    </div>
  );
};

export default Dropdown;

Usage:

const containerRefs= React.useRef([]);

{constants.home_services.map((service, index) => (
  <div
    className="w-full relative"
    key={index}
    ref={(el) => (containerRefs.current[index] = el)}
  >
    <div
      className={`${constants.static_sytles.bg_color_secondary_heavy} shadow-sm ${constants.static_sytles.shadow_secondary_heavy} px-4 py-2 rounded-md gap-y-2 border-2 border-[#9b9fab] flex justify-between items-center cursor-pointer`}
    >
      <h2 className="text-xl md:text-2xl font-light">{service.name}</h2>
      <img
        className="h-14 w-20 rounded-sm"
        src={service.ImgUrl}
        alt={service.name}
      />
    </div>
    <Dropdown
      watchElements={containerRefs.current}
      img={{ url: service.ImgUrl, alt: service.name }}
      btn_classes=""
      className=""
      img_classes="w-full rounded-sm h-80"
      content_wrapper_classes="rounded-lg"
      btn_child={
        <RiArrowDropDownFill
          className={`${constants.static_sytles.icon_color_secondary} ${constants.static_sytles.icon_size_sm}`}
        />
      }
    >
      <p className="mt-2 p-3">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusantium,
        quisquam voluptatem odio sapiente mollitia, autem nostrum quod vitae
        aliquam quam non exercitationem consequatur architecto distinctio
        numquam rerum odit. Nemo, eaque!
      </p>
    </Dropdown>
  </div>
))}

I have tried to use the watchElements prop to hold the references of external elements to attach eventListners and use them to toggle dropdowns

2

The main issues in the current code are:

  1. Each dropdown is receiving all container refs instead of just its
    own
  2. The event handling logic needs to be specific to each dropdown
    instance

Here are the necessary changes:

// ... imports remain the same

const Dropdown = ({
  content,
  img = {
    url: "",
    alt: ""
  },
  img_classes = "",
  btn_classes = "",
  className = "text-center",
  content_wrapper_classes = "",
  btn_child,
  children,
  watchElements = [] // This will now receive a single element instead of an array
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  const toggleDropdown = (event) => {
    setIsOpen((prev) => !prev);
  };

  const closeDropdown = () => {
    setIsOpen(false);
  };

  const handleClickOutside = (event) => {
    if (
      dropdownRef.current &&
      !dropdownRef.current.contains(event.target) &&
      !(watchElements && watchElements.contains && watchElements.contains(event.target))
    ) {
      closeDropdown();
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);

    // Add click listener to the single watch element
    if (watchElements) {
      watchElements.addEventListener("click", toggleDropdown);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      
      if (watchElements) {
        watchElements.removeEventListener("click", toggleDropdown);
      }
    };
  }, [watchElements]);

  // ... rest of the component remains the same
};

export default Dropdown;

And here’s how to modify the usage:

{constants.home_services.map((service, index) => (
  <div
    className="w-full relative"
    key={index}
    ref={(el) => (containerRefs.current[index] = el)}
  >
    <div
      className={`${constants.static_sytles.bg_color_secondary_heavy} shadow-sm ${constants.static_sytles.shadow_secondary_heavy} px-4 py-2 rounded-md gap-y-2 border-2 border-[#9b9fab] flex justify-between items-center cursor-pointer`}
    >
      <h2 className="text-xl md:text-2xl font-light">{service.name}</h2>
      <img
        className="h-14 w-20 rounded-sm"
        src={service.ImgUrl}
        alt={service.name}
      />
    </div>
    <Dropdown
      watchElements={containerRefs.current[index]} {/* Pass only the corresponding container ref */}
      img={{ url: service.ImgUrl, alt: service.name }}
      btn_classes=""
      className=""
      img_classes="w-full rounded-sm h-80"
      content_wrapper_classes="rounded-lg"
      btn_child={
        <RiArrowDropDownFill
          className={`${constants.static_sytles.icon_color_secondary} ${constants.static_sytles.icon_size_sm}`}
        />
      }
    >
      <p className="mt-2 p-3">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusantium,
        quisquam voluptatem odio sapiente mollitia, autem nostrum quod vitae
        aliquam quam non exercitationem consequatur architecto distinctio
        numquam rerum odit. Nemo, eaque!
      </p>
    </Dropdown>
  </div>
))}

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

React Dropdown Issue: All Dropdowns Open Simultaneously When Clicking Any Dropdown Button or External Elements

I am building a reusable dropdown component in React that can be toggled both by clicking its button and by clicking on external elements (watchElements). The dropdown works fine individually, but when I render multiple instances of the dropdown, clicking any button or external element toggles all dropdowns at once.

I want each dropdown instance to manage its own state independently so that clicking on a specific button or external element toggles only that specific dropdown.

Here is the current code for the Dropdown component:

import React, { useState, useEffect, useRef } from "react";

mport Button from "./Button";
import { RiArrowDownCircleFill } from "@remixicon/react";
import { constants } from "../constants";

const Dropdown = ({
  content,
  img = {
    url: "",
    alt: ""
  },
  img_classes = "",
  btn_classes = "",
  className = "text-center",
  content_wrapper_classes = "",
  btn_child = (
    <RiArrowDownCircleFill
      size={constants.static_sytles.icon_size_sm}
      className="text-white animate-bounce"
    />
  ),
  children,
  watchElements = []
}) => {
  const [isOpen, setIsOpen] = useState(false); 
  const dropdownRef = useRef(null);

  const toggleDropdown = (event) => {
    // console.log(dropdownRef.current)
    console.log('here is the event', event.target)
    console.log(dropdownRef.current.contains(event.target))
    if (dropdownRef.current && dropdownRef.current.contains(event.target)) {
      setIsOpen((prev) => !prev);
    }
  };

  const closeDropdown = () => {
    setIsOpen(false);
  };

  const handleClickOutside = (event) => {
    if (
      dropdownRef.current &&
      !dropdownRef.current.contains(event.target) &&
      !watchElements.some(
        (el) => el && el.contains && el.contains(event.target)
      )
    ) {
      closeDropdown();
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);

    if (watchElements.length) {
      watchElements.forEach((watchElement) => {
        if (watchElement) {
          watchElement.addEventListener("click", toggleDropdown);
        }
      });
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);

      if (watchElements.length) {
        watchElements.forEach((watchElement) => {
          if (watchElement) {
            watchElement.removeEventListener("click", toggleDropdown);
          }
        });
      }
    };
  }, [watchElements]);

  return (
    <div className={`${className}`}>
      <Button
        className={`${btn_classes} mt-3 flex items-center justify-center w-full`}
        // onClick={toggleDropdown}
        isDefault={false}
      >
        {btn_child}
      </Button>

      {/* Dropdown Menu */}
      <div
       ref={dropdownRef}
        className={` ${content_wrapper_classes} right-0 top-full w-full bg-white ring-opacity-5 overflow-hidden transition-all duration-700 ease-in-out ${
          isOpen  ?  "max-h-screen animate-flip-down" : "max-h-0"
        }`}
      >
        {img.url && (
          <img className={`${img_classes}`} src={img.url} alt={img.alt} />
        )}
        {children}
      </div>
    </div>
  );
};

export default Dropdown;

Usage:

const containerRefs= React.useRef([]);

{constants.home_services.map((service, index) => (
  <div
    className="w-full relative"
    key={index}
    ref={(el) => (containerRefs.current[index] = el)}
  >
    <div
      className={`${constants.static_sytles.bg_color_secondary_heavy} shadow-sm ${constants.static_sytles.shadow_secondary_heavy} px-4 py-2 rounded-md gap-y-2 border-2 border-[#9b9fab] flex justify-between items-center cursor-pointer`}
    >
      <h2 className="text-xl md:text-2xl font-light">{service.name}</h2>
      <img
        className="h-14 w-20 rounded-sm"
        src={service.ImgUrl}
        alt={service.name}
      />
    </div>
    <Dropdown
      watchElements={containerRefs.current}
      img={{ url: service.ImgUrl, alt: service.name }}
      btn_classes=""
      className=""
      img_classes="w-full rounded-sm h-80"
      content_wrapper_classes="rounded-lg"
      btn_child={
        <RiArrowDropDownFill
          className={`${constants.static_sytles.icon_color_secondary} ${constants.static_sytles.icon_size_sm}`}
        />
      }
    >
      <p className="mt-2 p-3">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusantium,
        quisquam voluptatem odio sapiente mollitia, autem nostrum quod vitae
        aliquam quam non exercitationem consequatur architecto distinctio
        numquam rerum odit. Nemo, eaque!
      </p>
    </Dropdown>
  </div>
))}

I have tried to use the watchElements prop to hold the references of external elements to attach eventListners and use them to toggle dropdowns

2

The main issues in the current code are:

  1. Each dropdown is receiving all container refs instead of just its
    own
  2. The event handling logic needs to be specific to each dropdown
    instance

Here are the necessary changes:

// ... imports remain the same

const Dropdown = ({
  content,
  img = {
    url: "",
    alt: ""
  },
  img_classes = "",
  btn_classes = "",
  className = "text-center",
  content_wrapper_classes = "",
  btn_child,
  children,
  watchElements = [] // This will now receive a single element instead of an array
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  const toggleDropdown = (event) => {
    setIsOpen((prev) => !prev);
  };

  const closeDropdown = () => {
    setIsOpen(false);
  };

  const handleClickOutside = (event) => {
    if (
      dropdownRef.current &&
      !dropdownRef.current.contains(event.target) &&
      !(watchElements && watchElements.contains && watchElements.contains(event.target))
    ) {
      closeDropdown();
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);

    // Add click listener to the single watch element
    if (watchElements) {
      watchElements.addEventListener("click", toggleDropdown);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      
      if (watchElements) {
        watchElements.removeEventListener("click", toggleDropdown);
      }
    };
  }, [watchElements]);

  // ... rest of the component remains the same
};

export default Dropdown;

And here’s how to modify the usage:

{constants.home_services.map((service, index) => (
  <div
    className="w-full relative"
    key={index}
    ref={(el) => (containerRefs.current[index] = el)}
  >
    <div
      className={`${constants.static_sytles.bg_color_secondary_heavy} shadow-sm ${constants.static_sytles.shadow_secondary_heavy} px-4 py-2 rounded-md gap-y-2 border-2 border-[#9b9fab] flex justify-between items-center cursor-pointer`}
    >
      <h2 className="text-xl md:text-2xl font-light">{service.name}</h2>
      <img
        className="h-14 w-20 rounded-sm"
        src={service.ImgUrl}
        alt={service.name}
      />
    </div>
    <Dropdown
      watchElements={containerRefs.current[index]} {/* Pass only the corresponding container ref */}
      img={{ url: service.ImgUrl, alt: service.name }}
      btn_classes=""
      className=""
      img_classes="w-full rounded-sm h-80"
      content_wrapper_classes="rounded-lg"
      btn_child={
        <RiArrowDropDownFill
          className={`${constants.static_sytles.icon_color_secondary} ${constants.static_sytles.icon_size_sm}`}
        />
      }
    >
      <p className="mt-2 p-3">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusantium,
        quisquam voluptatem odio sapiente mollitia, autem nostrum quod vitae
        aliquam quam non exercitationem consequatur architecto distinctio
        numquam rerum odit. Nemo, eaque!
      </p>
    </Dropdown>
  </div>
))}

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

React Dropdown Issue: All Dropdowns Open Simultaneously When Clicking Any Dropdown Button or External Elements

I am building a reusable dropdown component in React that can be toggled both by clicking its button and by clicking on external elements (watchElements). The dropdown works fine individually, but when I render multiple instances of the dropdown, clicking any button or external element toggles all dropdowns at once.

I want each dropdown instance to manage its own state independently so that clicking on a specific button or external element toggles only that specific dropdown.

Here is the current code for the Dropdown component:

import React, { useState, useEffect, useRef } from "react";

mport Button from "./Button";
import { RiArrowDownCircleFill } from "@remixicon/react";
import { constants } from "../constants";

const Dropdown = ({
  content,
  img = {
    url: "",
    alt: ""
  },
  img_classes = "",
  btn_classes = "",
  className = "text-center",
  content_wrapper_classes = "",
  btn_child = (
    <RiArrowDownCircleFill
      size={constants.static_sytles.icon_size_sm}
      className="text-white animate-bounce"
    />
  ),
  children,
  watchElements = []
}) => {
  const [isOpen, setIsOpen] = useState(false); 
  const dropdownRef = useRef(null);

  const toggleDropdown = (event) => {
    // console.log(dropdownRef.current)
    console.log('here is the event', event.target)
    console.log(dropdownRef.current.contains(event.target))
    if (dropdownRef.current && dropdownRef.current.contains(event.target)) {
      setIsOpen((prev) => !prev);
    }
  };

  const closeDropdown = () => {
    setIsOpen(false);
  };

  const handleClickOutside = (event) => {
    if (
      dropdownRef.current &&
      !dropdownRef.current.contains(event.target) &&
      !watchElements.some(
        (el) => el && el.contains && el.contains(event.target)
      )
    ) {
      closeDropdown();
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);

    if (watchElements.length) {
      watchElements.forEach((watchElement) => {
        if (watchElement) {
          watchElement.addEventListener("click", toggleDropdown);
        }
      });
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);

      if (watchElements.length) {
        watchElements.forEach((watchElement) => {
          if (watchElement) {
            watchElement.removeEventListener("click", toggleDropdown);
          }
        });
      }
    };
  }, [watchElements]);

  return (
    <div className={`${className}`}>
      <Button
        className={`${btn_classes} mt-3 flex items-center justify-center w-full`}
        // onClick={toggleDropdown}
        isDefault={false}
      >
        {btn_child}
      </Button>

      {/* Dropdown Menu */}
      <div
       ref={dropdownRef}
        className={` ${content_wrapper_classes} right-0 top-full w-full bg-white ring-opacity-5 overflow-hidden transition-all duration-700 ease-in-out ${
          isOpen  ?  "max-h-screen animate-flip-down" : "max-h-0"
        }`}
      >
        {img.url && (
          <img className={`${img_classes}`} src={img.url} alt={img.alt} />
        )}
        {children}
      </div>
    </div>
  );
};

export default Dropdown;

Usage:

const containerRefs= React.useRef([]);

{constants.home_services.map((service, index) => (
  <div
    className="w-full relative"
    key={index}
    ref={(el) => (containerRefs.current[index] = el)}
  >
    <div
      className={`${constants.static_sytles.bg_color_secondary_heavy} shadow-sm ${constants.static_sytles.shadow_secondary_heavy} px-4 py-2 rounded-md gap-y-2 border-2 border-[#9b9fab] flex justify-between items-center cursor-pointer`}
    >
      <h2 className="text-xl md:text-2xl font-light">{service.name}</h2>
      <img
        className="h-14 w-20 rounded-sm"
        src={service.ImgUrl}
        alt={service.name}
      />
    </div>
    <Dropdown
      watchElements={containerRefs.current}
      img={{ url: service.ImgUrl, alt: service.name }}
      btn_classes=""
      className=""
      img_classes="w-full rounded-sm h-80"
      content_wrapper_classes="rounded-lg"
      btn_child={
        <RiArrowDropDownFill
          className={`${constants.static_sytles.icon_color_secondary} ${constants.static_sytles.icon_size_sm}`}
        />
      }
    >
      <p className="mt-2 p-3">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusantium,
        quisquam voluptatem odio sapiente mollitia, autem nostrum quod vitae
        aliquam quam non exercitationem consequatur architecto distinctio
        numquam rerum odit. Nemo, eaque!
      </p>
    </Dropdown>
  </div>
))}

I have tried to use the watchElements prop to hold the references of external elements to attach eventListners and use them to toggle dropdowns

2

The main issues in the current code are:

  1. Each dropdown is receiving all container refs instead of just its
    own
  2. The event handling logic needs to be specific to each dropdown
    instance

Here are the necessary changes:

// ... imports remain the same

const Dropdown = ({
  content,
  img = {
    url: "",
    alt: ""
  },
  img_classes = "",
  btn_classes = "",
  className = "text-center",
  content_wrapper_classes = "",
  btn_child,
  children,
  watchElements = [] // This will now receive a single element instead of an array
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  const toggleDropdown = (event) => {
    setIsOpen((prev) => !prev);
  };

  const closeDropdown = () => {
    setIsOpen(false);
  };

  const handleClickOutside = (event) => {
    if (
      dropdownRef.current &&
      !dropdownRef.current.contains(event.target) &&
      !(watchElements && watchElements.contains && watchElements.contains(event.target))
    ) {
      closeDropdown();
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);

    // Add click listener to the single watch element
    if (watchElements) {
      watchElements.addEventListener("click", toggleDropdown);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      
      if (watchElements) {
        watchElements.removeEventListener("click", toggleDropdown);
      }
    };
  }, [watchElements]);

  // ... rest of the component remains the same
};

export default Dropdown;

And here’s how to modify the usage:

{constants.home_services.map((service, index) => (
  <div
    className="w-full relative"
    key={index}
    ref={(el) => (containerRefs.current[index] = el)}
  >
    <div
      className={`${constants.static_sytles.bg_color_secondary_heavy} shadow-sm ${constants.static_sytles.shadow_secondary_heavy} px-4 py-2 rounded-md gap-y-2 border-2 border-[#9b9fab] flex justify-between items-center cursor-pointer`}
    >
      <h2 className="text-xl md:text-2xl font-light">{service.name}</h2>
      <img
        className="h-14 w-20 rounded-sm"
        src={service.ImgUrl}
        alt={service.name}
      />
    </div>
    <Dropdown
      watchElements={containerRefs.current[index]} {/* Pass only the corresponding container ref */}
      img={{ url: service.ImgUrl, alt: service.name }}
      btn_classes=""
      className=""
      img_classes="w-full rounded-sm h-80"
      content_wrapper_classes="rounded-lg"
      btn_child={
        <RiArrowDropDownFill
          className={`${constants.static_sytles.icon_color_secondary} ${constants.static_sytles.icon_size_sm}`}
        />
      }
    >
      <p className="mt-2 p-3">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusantium,
        quisquam voluptatem odio sapiente mollitia, autem nostrum quod vitae
        aliquam quam non exercitationem consequatur architecto distinctio
        numquam rerum odit. Nemo, eaque!
      </p>
    </Dropdown>
  </div>
))}

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật