react-useportal: Trigger openPortal or any action without event

I’m trying to openPortal on route change. When route changes, I get; You must either add a ref to the element you are interacting with or pass an event to openPortal(e) or togglePortal(e).

How do I do it without ref or event?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 19 (5 by maintainers)

Most upvoted comments

I have a similar use case where a modal can be opened programmatically without user interaction when an API returns an error response. It would be great to support this when you get a chance @alex-cory.

In the meantime @Sebastp I am using something like this as a workaround:

import React, { useEffect } from 'react';
import usePortal from 'react-useportal';

// Passing this to openPortal tricks it into thinking it was from a user
const NULL_EVENT = { currentTarget: true };

const Modal = () => {
  const { openPortal, closePortal, isOpen, Portal } = usePortal();

  useEffect(() => {
    openPortal(NULL_EVENT);
  }, []);

  return (
    isOpen && (
      <Portal>
        <div>
          This will open immediately
       	  <button onClick={closePortal}>close</button>
		</div>
      </Portal>
    )
  );
};

I will get to this as soon as I can. Apologies for it taking so long.

It turns out NULL_EVENT isn’t foolproof, but to avoid Uncaught TypeError: target.current.contains is not a function you could try this:

const NULL_EVENT = { currentTarget: { contains: () => false } };

@alex-cory have you had a chance to look at this? Would you accept a PR?

+1

I will take a look at this asap. Swamped with work right now 😕