Issue with activating a Modal through a button inside a table row on React

I'm currently working on two files: Modal.js and Users.js. Users.js features a table with an API get query linked to it, and in the last column of the table, there's a dropdown for each row that contains three buttons: View, Edit, and Delete. My goal is to have the Delete button trigger a Modal with a confirmation message saying "Are you sure you wish to delete the user?".

I've been facing challenges trying to make the Modal appear upon clicking the Delete component in the Users.js file. I will provide the code for both files below.

Modal.js (The content within the modal has not been modified yet)

import {
  CButton,
  CModal,
  CModalHeader,
  CModalTitle,
  CModalBody,
  CModalFooter,
} from "@coreui/react";

const Modal = ({ visible, setVisible }) => {
  return (
    <>
      <CModal visible={visible} onClose={() => setVisible(false)}>
        <CModalHeader onClose={() => setVisible(false)}>
          <CModalTitle>Modal title</CModalTitle>
        </CModalHeader>
        <CModalBody>Woohoo, you're reading this text in a modal!</CModalBody>
        <CModalFooter>
          <CButton color="secondary" onClick={() => setVisible(false)}>
            Close
          </CButton>
          <CButton color="primary">Save changes</CButton>
        </CModalFooter>
      </CModal>
    </>
  );
};

export default Modal;

Users.js

<CTableRow v-for="item in tableItems" key={rows.userID}>
  <CTableDataCell className="text-center">{rows.userID}</CTableDataCell>
  <CTableDataCell>{rows.firstName}</CTableDataCell>
  <CTableDataCell>
    <div>{rows.lastName}</div>
  </CTableDataCell>
  <CTableDataCell className="column-overflow">{rows.email}</CTableDataCell>
  <CTableDataCell>{rows.role}</CTableDataCell>
  <CTableDataCell>{rows.createdAt}</CTableDataCell>
  <CTableDataCell>{rows.updatedAt}</CTableDataCell>

  <CTableDataCell>
    <strong>{rows.lastLogin}</strong>
  </CTableDataCell>
  <CTableDataCell>
    <CDropdown>
      <CDropdownToggle color="transparent"></CDropdownToggle>
      <CDropdownMenu>
        <CDropdownItem className="dropdown-item pointer">View</CDropdownItem>
        <CDropdownItem className="dropdown-item pointer">Edit</CDropdownItem>

        <CDropdownItem
          className="dropdown-item text-danger pointer"
          onClick={() => Modal()} <- The issue lies here
        >
          Delete
        </CDropdownItem>
      </CDropdownMenu>
    </CDropdown>
  </CTableDataCell>
</CTableRow>;

I would greatly appreciate any help or guidance on this matter. Feel free to ask if you need additional code snippets (I've omitted most of the Users.js file as it's quite lengthy) except for the specific row to give you an idea of the Delete button's location.

Thank you in advance!

Answer №1

The Modal element must be present on the page with a visible attribute that is controlled by the parent component (not invoked as a function). The CoreUI examples for the CModal may not align perfectly with your specific requirements. It is recommended to utilize the useState hook in your parent component named Users and pass a setter callback to handle the close event of the Modal.

For instance:

Users.js

const Users = () => {
  const [visible, setVisible] = React.useState(false);
  const [selectedUser, setSelectedUser] = React.useState(null);

  const rows = [
    { userID: "1", firstName: "Cameron", lastName: "E" },
    { userID: "2", firstName: "Steve", lastName: "G" }
  ];

  return (
    <>
      <CTable>
        {rows.map((row) => {
          return (
            <CTableRow v-for="item in tableItems" key={row.userID}>
              <CTableDataCell className="text-center">
                {row.userID}
              </CTableDataCell>
              <CTableDataCell>{row.firstName}</CTableDataCell>
              <CTableDataCell>
                <div>{row.lastName}</div>
              </CTableDataCell>
              <CTableDataCell className="column-overflow">
                {row.email}
              </CTableDataCell>
              <CTableDataCell>{row.role}</CTableDataCell>
              <CTableDataCell>{row.createdAt}</CTableDataCell>
              <CTableDataCell>{row.updatedAt}</CTableDataCell>

              <CTableDataCell>
                <strong>{row.lastLogin}</strong>
              </CTableDataCell>
              <CTableDataCell>
                <CDropdown>
                  <CDropdownToggle color="transparent">
                    Dropdown button
                  </CDropdownToggle>
                  <CDropdownMenu>
                    <CDropdownItem className="dropdown-item pointer">
                      View
                    </CDropdownItem>
                    <CDropdownItem className="dropdown-item pointer">
                      Edit
                    </CDropdownItem>

                    <CDropdownItem
                      className="dropdown-item text-danger pointer"
                      onClick={() => {
                        setSelectedUser(row);
                        setVisible(true);
                      }}
                    >
                      Delete
                    </CDropdownItem>
                  </CDropdownMenu>
                </CDropdown>
              </CTableDataCell>
            </CTableRow>
          );
        })}
      </CTable>
      <Modal
        visible={visible}
        user={selectedUser}
        onClose={() => setVisible(false)}
      />
    </>
  );
};

Modal.js

const Modal = ({ visible, onClose, user }) => {
  return (
    <>
      <CModal visible={visible} onClose={onClose}>
        <CModalHeader onClose={onClose}>
          <CModalTitle>Delete {user.firstName}?</CModalTitle>
        </CModalHeader>
        <CModalBody>
          Are you sure you want to delete {user.firstName}? (He's a good guy.)
        </CModalBody>
        <CModalFooter>
          <CButton color="secondary" onClick={onClose}>
            Yeah he is a good guy
          </CButton>
          <CButton color="primary">Nuke 'Em!</CButton>
        </CModalFooter>
      </CModal>
    </>
  );
};

Note: Additionally, I have included an illustration of how to transmit the selected user data to the Modal, ensuring only one instance of the Modal component is present on the page.

Working CodeSandbox: https://codesandbox.io/s/cold-leftpad-l5ivqy?file=/src/Modal.js

Rendered Users.js https://i.stack.imgur.com/YBz0t.png

Rendered Modal.js https://i.stack.imgur.com/9Kidw.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...

Solving the error message "window is not defined" in Nextjs

Hey, I'm attempting to create a component similar to [this tutorial][1] in my NextJS app but I'm running into an error ReferenceError: window is not defined //Navbar.js import styles from "../styles/Navbar.module.css"; export default fu ...

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...

Is there a way to add CSS styles to all div elements except for those that are contained within a parent div with a certain class

I have a universal CSS that impacts all div elements, but I need to exclude the divs within a parent div that has a specific class, like in this instance where it's the "should-not-apply" class. div { font-size: 20px !important; font-weight: 50 ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Looking to deactivate the entire keyboard with JavaScript? Make sure that the start key is not disabled, not even Ctrl

Despite my efforts to disable the entire keyboard using JavaScript, I have encountered some limitations. The Windows Start key and Enter key are not being disabled by my script. <script type='text/javascript'> document.onkeydown = functi ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

Inconsistent behavior between Chrome and Firefox when using AngularJS $resource GET method: success in Chrome but error

I am currently working on a simple custom GET request in Angular using $resource angular.module('myApp') .factory('MyService', function($resource){ return $resrouce('some url', {}, { list: {method:'G ...

Learn how to send data from a MySQL server to a Node.js application using Socket.IO

I've been facing a challenge recently. I am attempting to listen for events from the @rodrigogs/my-sql events node package and then emit those events through socket-io to the react client. However, there seems to be a disconnect that I can't see ...

Looks like there was an error with the start script for [email protected]

I am facing an error in my React application's client side directory where node_modules are installed. The app was working fine until 2 weeks ago, but now when I try to run 'npm start', it fails to launch. The error message in the terminal i ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

Is Mobile Safari causing issues with React PWA when uploading images?

We were surprised by the lack of information online regarding this issue, so we are reaching out here in hopes of finding a solution. When using an iPhone with mobile safari, we encountered a problem while running two simple tests. One test works fine, wh ...

Is there a way to postpone the action so that the bot will not acknowledge the second command until after I have completed the first command

client.on('message', async (message) => { let author = message.author.username if (message.author.bot) return; if (message.content.startsWith('-queue open ')) { message.content = message.content.replace('-queue o ...

Issue encountered when using exports in a React project - Uncaught ReferenceError: exports is not recognized

Recently, as I began my journey with React.js, I encountered a perplexing error. Within my project, there is a file that exports a function in the following format: exports.building = { //... //Something goes here... }; To import this function, I uti ...

Rhino's env.js causes the anchor element's pathname to be undefined

Encountered an issue that appears to be related to how anchor tags are implemented in Rhino. Despite using env.js, there might be a configuration error causing the problem. The issue arises when writing unit tests for code designed for an angularjs applic ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

Adjust the appearance of a div according to the input value

When a user inputs the correct value (a number) into an input of type "number," I want a button to appear. I attempted var check=document.getElementById("buttonID").value == "1" followed by an if statement, but it seems I made a mistake somewhere. Here&ap ...

Is there a way to determine if a chosen date and time are prior or subsequent to the current date and time in an AngularJS environment?

When using a datepicker and timepicker, I have obtained a selected date and time. Now, I need to determine if this selected date and time is before or after the current date and time. For example, if the selected date is "Sat Dec 12 2015" and the selected ...

Having difficulties setting up React JS on my Windows X64 operating system

Looking to set up React JS with the npx command...I attempted to install React JS by running these commands...but unfortunately, it doesn't seem to be successfully installing React after reaching the last two lines shown in the image. ...

An error occurred while validating Redux Form due to using field names such as user.name

In my React component, I have a Redux form structured like this: <div className="col-sm-12"> <div className="form-group row"> <div className="col-sm-4"> <label>A. Name</label> </div> <div className="col-sm- ...