soccerway
soccerway

Reputation: 11961

Call a material ui dialog

How to call a Material UI Dialog during onClick on delete icon ie onClick={deletePlayer(id)} ?

I have added the Dialog.js under modal/Dialog and imported to Home component.

I have added a demo here

Upvotes: 0

Views: 1646

Answers (2)

Thomas Hennes
Thomas Hennes

Reputation: 9939

Short answer: Forked CodeSandbox with working dialog

Long answer:

First of all, you need to move the display/dismiss logic out of the AlertDialog component and into the component that actually triggers the display of the modal (in your case, the Home component). This means that you'll receive the open state and onClose handler as props (along with the playerId which will hold the ID of the player being targeted for deletion). So the signature of your dialog component becomes:

export default function AlertDialog({ open, onClose, playerId }) {
  return (
    <Dialog open={open} onClose={onClose} ...> ... </Dialog>
  );
}

In Home, we add the logic to track and set the state of both the dialog open/closed status, and the ID of the player targeted for deletion. We do this through useState:

  const [deleteDialog, setDeleteDialog] = useState(false);
  const [playerId, setPlayerId] = useState("");

While you could have as many AlertDialog components as you have players by adding <AlertDialog /> inside your player map loop, it is redundant as you'll only ever have one modal active (by definition). So all you have to do is place a single instance of <AlertDialog /> in your Home component. A good convention is to place it before the closing encompassing tag:

  return (
    <div className="App">
      .
      .
      .
      <AlertDialog
        open={deleteDialog}
        onClose={() => setDeleteDialog(false)}
        playerId={playerId}
      />
    </div>
  );

Finally, we deal with the handler responsible for displaying the modal, in your case deletePlayer. We have two things to do there: set the player ID targeted for deletion through the playerId state variable, and display the modal through the deleteDialog state variable:

  const deletePlayer = id => e => {
    setPlayerId(id);
    setDeleteDialog(true);
  };

Upvotes: 1

Fraction
Fraction

Reputation: 12954

Create a state in the Home component to handle the Dialog visibility, set the state on click and render the AlertDialog conditionally:

const [openDialog, setOpenDialog] = useState(false);

...

const deletePlayer = id => e => {
  setOpenDialog(true);
};

...

return(
  ...

  {openDialog && (
    <AlertDialog isOpen={openDialog} setIsOpen={setOpenDialog} />
  )}

Then in the AlertDialog component:

export default function AlertDialog(props) {
  const { isOpen, setIsOpen } = props;

  const handleClose = () => {
    setIsOpen(false);
  };

  return (
    <div>
      <Dialog
        open={isOpen}
        onClose={handleClose}
  ...

Working Example:

Edit interesting-rain-ed09o

Upvotes: 1

Related Questions