react-modal-hook icon indicating copy to clipboard operation
react-modal-hook copied to clipboard

Add a way to pass a variable through showModal

Open gajus opened this issue 4 years ago • 2 comments

Related to https://github.com/mpontus/react-modal-hook/issues/30

I need to pass variable to useModal constructor from invocation of showModal, which has access to the parent context.

gajus avatar Jul 26 '20 00:07 gajus

As a very dirty workaround I've used:

// @see https://github.com/mpontus/react-modal-hook/issues/31
global.snackMeetingParticipantUid = snackMeetingParticipant?.uid;

const [showReportProblem, hideReportProblem] = useModal(() => {
  invariant(global.snackMeetingParticipantUid, 'Snack meeting participant is not available.');

  return <ReportProblem
    onClose={hideReportProblem}
    snackMeetingParticipantUid={global.snackMeetingParticipantUid}
  />;
});

gajus avatar Jul 26 '20 00:07 gajus

It looks like you can pass dependencies to the useModal hook like this:

useModal(
  () => <>...</>,
  [dependency1, dependency2, ...]
);

Here is something that worked for me:

const MyComponent = () => {
  const [foo, setFoo] = useState('foo');

  const [showModal, hideModal] = useModal(
    () => (
      <>
        <p>{foo}</p>
        <button
          onClick={() => {
            setFoo("bar");
          }}
        >
          Change foo to bar
        </button>
      </>
    ),
    [foo]
  );
  
  return <button onClick={showModal}>Show modal</button>;
};

ThisNameWasTaken avatar Dec 30 '20 10:12 ThisNameWasTaken