How can I open the modal when I click the delete button?

Viewed 100

I'm trying to open a modal(which says are you sure you want to delete the client) when a user clicks the button to delete the client. To open the modal I have created a openModal function, but not sure how to call this function, in this code.

ClientList.js

export default function ListClients() {
 const [showModal, setShowModal] = useState();
 const [userlist, setUserlist] = useState([]);
 const [selectedID,setSelectedID]=useState('');

   function deleteClient() {
   if(selectedID){
       const userParams = {
          clientName:
        clientName,
          country: country,
          clientid: selectedID,
        };
        
       axios
          .delete(process.env + "client", {
        data: clientParams,
          })
          .then((response) => {
        setClientlist(clientlist.filter((client) => client.id !== clientId));
          })
          .catch((error) => {
        console.log(error);
          });
   }



  }

return(
     <div>
    <tbody>
        {userlist.length > 0 ? (
           userlist.map((userlist) => (
             <tr key={userlist.id}>
                <td>
                  <div">
                      {userlist.id}
                   </div>
                </td>
                <td>
                  <button type="button" onClick={() => setSelectedID(userlist.id)}> 
                      Delete
                  </button>
                 </td
             </tr>
        </tbody>

         //the idea is to pass the  state for modal to show 
       <ModalDelete showModal={showModal} setShowModal={setShowModal} onCancel={()=>setSelectedID('')} onDel={deleteClient}/>
      </div>
);

ModalDelete.js

export default function ModalDelete({ showModal, setShowModal,onCancel,onDel }) {
 
return(
  <div>
    { showModal ? <Transition.Root show={showModal}>  
       <div>
       <p> Are you sure you want to delete the client?</p>
    </div>

    <div>
        <button type="button" onClick={onDel}>Yes</button>
            <button type="button" onClick={() => {
            setShowModal(false);
            onCancel();
            }} >
              Go Back
            </button>
          </div>
    </Transition.Root> : null }
  </div>
);
}

How can I call the function in this code, to open the modal when the deleted button is clicked?

1 Answers

You simply could do this on the delete button (you wouldn't need that openModal):

 <button
  type="button" 
  onClick={() => {
    setSelectedID(userlist.id);
    setShowModal(true);
   }}
 >
  Delete
 </button>
Related