0

I have tried several approaches, but it seems like I don't understand something or missing something else.

The idea: I have a navbar with some URLs that contain a hash, and upon click I'd like the one with the same data-id attribute to open.

const serviceIds = pageContent[locale as string]?.services.map(
    (service: { id: unknown }) => service.id
  );
  const hash = asPath.split("#")[1] || "legal-consultancy";
  const serviceIndex = serviceIds?.indexOf(hash);
  const disclosureRefs = useMemo(() => {
    return (
      serviceIds?.map(() => {
        return createRef<HTMLButtonElement>();
      }) ?? []
    );
  }, [serviceIds]);
  const disclosureRef = disclosureRefs[serviceIndex as number];

  function handleClosingOthers(id: string) {
    const otherRefs = disclosureRefs.filter((ref) => {
      return ref.current?.dataset.id !== id;
    });

    otherRefs.forEach((ref) => {
      const isOpen = ref.current?.dataset.open === "true";

      if (isOpen) {
        ref.current?.click();
      }
    });
  }

  function handleDisclosureClick(event: React.MouseEvent<HTMLButtonElement>) {
    const id = event.currentTarget.dataset.id as string;
    const isOpen = event.currentTarget.dataset.open === "true";

    handleClosingOthers(id);
    event.currentTarget.setAttribute("data-open", `${!isOpen}`);
  }

  useEffect(() => {
    if (disclosureRef?.current) {
      disclosureRef.current.scrollIntoView({ behavior: "smooth" });
      disclosureRef.current.focus();
      disclosureRef.current.click();
    }
  }, [disclosureRef]);

The right element is selected by disclosureRef.current, as the screen scrolls correctly, and I am able to expand the focus() Disclosure by pressing Enter or Space, but the click() to actually open it does absolutely nothing.

The Disclosure.Button is rendered with as={React.Fragment} with a button element containing the ref={disclosureRefs[index]}.

Rob Csaszar
  • 43
  • 10

0 Answers0