0

How can I show the modal only based on card was clicked?

I have this dynamic card. Once I clicked on a specific card, how can it show the modal with a title of the data's id? As of now, once I click on a card, it will only show the last id.

Main app

 const [isOpen, setisOpen] = useState(false);

  const handleOpen = (id) => {
    console.log(id);
    setOpen(true)
  };

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

....

 {data.map((i) => (
          <Grid
            key={data.indexOf(i)}
          >
            <CardonClick={(e) => handleOpen(i.id)}>
              <CardHeader title={i.title} />
            </Card>

            <Modal isOpen={isOpen} handleClose={handleClose} title={i.id}/> <-- display of the id here
          </Grid>
        ))}

Modal reusable component

import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          No
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;
Shoppe
  • 39
  • 1
  • 5
  • 3
    Do this post answer your question? https://stackoverflow.com/questions/67725086/how-do-i-use-react-modal-with-a-map-function – PakDragoon Aug 24 '22 at 11:50

1 Answers1

0

You can use useState hook and store the relevant data (id in your case) in handleOpen function. Then you can use that data in your modal. example:

  const [isOpen, setisOpen] = useState(false);
  const [currentModalId,setCurrentModalId]=useState("");

  const handleOpen = (id) => {
    console.log(id);
    setCurrentModalId(id);
    setOpen(true)
  };

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

And then use it:

...<Modal> <div> {id} </Modal>