How do I add modal for a delete popup?

232 Views Asked by At

I'm new to react and now I'm trying to make the delete alert as a modal, can anyone tell me where do I put it?

   const handleDelete = (id) => {
    const confirm = window.confirm("Delete this ?");
    if(confirm) {
      axios.delete('https://64d9e02de947d30a380a6a16.mockapi.io/todos/' +id)
      .then(res => {
        navigate("/");
      })
      .catch(err => console.log(err));
    }
      }
    
        return (
<div> 
<thead>
<tr>
<th>name</th>
</thead>
<tbody>
<tr>
<td>{data.id}</td>
<td>
         <button onClick={e => handleDelete(data.id)} className='btn btn-sm'>Delete</button>
</td>
</tr>
1

There are 1 best solutions below

0
Jayesh Cholkar On

You can do like this:

import { useState } from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';

function Example() {
const [show, setShow] = useState(false);

const handleClose = () => setShow(false);

const handleShow = () => setShow(true);
 
const handleDelete = (id) => {
if(id) {
  axios.delete('https://64d9e02de947d30a380a6a16.mockapi.io/todos/' +id)
  .then(res => {
    navigate("/");
  })
  .catch(err => console.log(err));
}
  }

return (
<>
  <Button variant="primary" onClick={handleShow}>
    Delete
  </Button>

  <Modal show={show} onHide={handleClose}>
    <Modal.Header closeButton>
      <Modal.Title>Modal heading</Modal.Title>
    </Modal.Header>
    <Modal.Body>Woohoo, you are reading this text in a modal! 
  </Modal.Body>
    <Modal.Footer>
      <Button variant="secondary" onClick={handleClose}>
        Close
      </Button>
      <Button variant="primary" onClick={() => handleDelete(id)}>
        Confirm Delete
      </Button>
    </Modal.Footer>
  </Modal>
  </>
 );
}

export default Example;

This is an example you can modify according to your need.