close multiple nested Material UI dialogs with browser back button - reactjs

Viewed 1407

i want to toggle a material ui Dialog visibility base on URL. for example when URL is somthing like this site.com/#UKLMCBUWPO modal one be visible and when site.com/#UKLMCBUWPO&KLMCnhjmWPO modal two be visible and each time user click the browser back button last state in url pops and the second modal be hidden and so on. basically user can interact with browser back and forward buttons to show and hide the dialog. i just want some gibberish text in URL when modals open and the gibrish removed when they closed until no modals are shown on the page.

any ideas ?

2 Answers

You can use HashRouter to configure the router and props.location.hash to get hash link and split it and get the last item in the array.

Working demo

Navs

     <Link
        className={
          "tab " + currentRoute.includes("about") ? "tab active" : "tab"
        }
        to="/modal#state=KLMCnhjmWPO"
      >
        Go to Modal 1
      </Link>
      <Link
        className={
          "tab " + currentRoute.includes("contact") ? "tab active" : "tab"
        }
        to={{
          pathname: "/modal",
          hash: "#state=KLMCnhjmWPO&#state=UKLMCBUWPO"
        }}
      >
        Go to Modal 2
      </Link>

Routes

<HashRouter>
        <Nav />
        <Switch>
          <Route path="/home" exact component={Home} />
          <Route path="/modal" exact component={Modal} />
        </Switch>
      </HashRouter>

Sample Modal

const Modal = props => {
  const lastModal = props.location.hash.split("&");
  return <div>Modal - {lastModal[lastModal.length - 1]}</div>;
};

after some research i came up with this solution.

basically i keep tracking of the modals using UUID in a singleton class. then i create a dialog class and using Material UI Dialog and custom history, i listen to route changes and dialog open state and then update the singleton array. here is my code:

working codesandbox Example

Related