Home > database >  How to render a new popup every time I clicked Grid?
How to render a new popup every time I clicked Grid?

Time:12-20

The problem is... The first popup renders fine. But when I try to render the second popup, it's not working. A new popup is not invoked, the previous popup is refreshed.

I want to call a new popup when I clicked a cell in the grid.

my code is like this

const Main = () => {
    const [isPopupOpen, setIsPopupOpen] = useState(false);

return (
    <>
    ... other components (including grid)
    { isPopupOpen && <Popup />}
    </>
 )
};

when Grid is Clicked, 'isPopupOpen' is updated to true.

I use 'react-new-window' library, and this library use 'window.open()' ((https://github.com/rmariuzzo/react-new-window)

so I set different window names to call several popups.

but I can't solve the problem.

I try to set a state object that has a boolean value.

const [popupObj, setPopupObj] = useState({});

when the grid is clicked, popupObj updates like

{'cellA': true, 'cellD': true}

and a return statement is like

{popupObj[cellName] && <Popup /> }

but the result was the same.

what should I do to solve this problem?

CodePudding user response:

You need to add your popup in an array, so you can render many popup as you want, then you need to define in How much time you will remove a added popup from array or add a close button

Extra: you can configure in global state to access in all your application to your popups and you will have a component like this: https://www.npmjs.com/package/notistack

CodePudding user response:

I wrote an example for you. Hope it helps.

  • use popupIds state to store the popups that you want to open
  • use Set to toggle the popupIds in the addPopup click handler
import * as React from "react";

export default function App() {
  const [popupIds, setPopupIds] = React.useState([]);

  const addPopup = (popupId) => {
    const set = new Set(popupIds);
    if (set.has(popupId)) {
      set.delete(popupId);
    } else {
      set.add(popupId);
    }
    setPopupIds(Array.from(set));
  };

  return (
    <div className="App">
      {["hello", "react"].map((popupId) => (
        <div onClick={() => addPopup(popupId)}>{popupId}</div>
      ))}
      {popupIds.map((popupId) => (
        <Popup title={getPopupTitle(popupId)} />
      ))}
    </div>
  );
}

const getPopupTitle = (popupId) => `title for ${popupId}`;

const Popup = ({ title }) => <div>{title}</div>;

Here is a codesandbox that you can play with directly.

  • Related