How to make a reusable & tab focusable React modal using portal

171 Views Asked by At

I have a modal created with react-dom portal and this is being used more than once to display different modals.

 <>
      <button onClick={OnClick}>
        {icon}
      </button>
      {isOpen &&
        createPortal(
          <div tabIndex={-1}>
              <button onClick={handleClose}>
                <CloseIcon />
              </button>
            </div>
            <div>{children}</div>
          </div>,
          document.body,
        )}
    </>

I'm passing different contents to the children (input, anchor, button) in different modals.
And (1) once the modal is opened > (2) press tab key, I want the (3) first focusable-element > (4) to the last element > (5) close icon button focused in the modal. I've passed tabIndex to the portal div like the pasted code, but this didn't work. I guess it's because I'm using the modals in many places (max 3) and they exists in the DOM tree. How can I make this generic modal tab-focusable?

Thank you.

0

There are 0 best solutions below