Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup.

export const specificColumn = [
  {
    field: "price",
    headerName: "Price",
    flex: 1,
    cellClassName: "name-column--cell",
  },
  {
    field: ""editPrice"",
    headerName: "Edit Price",
    flex: 1,
    editable: false,
    renderCell: (params) => {
      return (
        <FiEdit onClick={() => alert(params.row.price)} /> //I want to open modal with the ID as a parameter} className='cursor-pointer' />
      );
    },
  },
];

Within the component that contains the Datagrid, I've included an openModal function intended to display the modal.

const openModal = () => {
  setShowModal(true);
}

This represents my Datagrid

<DataGrid
  autoHeight
  rows={someArray}
  columns={someColumn}
  slots={{ toolbar: CustomToolbar }}
/>;

What steps can I take to ensure the button triggers the opening of the modal? Your assistance would be greatly appreciated.

Thank you.

Answer №1

As outlined in the instructions:

The renderCell function should return a React node, rather than a React component.

To incorporate React hooks within your renderer, it's recommended to enclose them inside a component.

You can develop a personalized component that displays both the button and modal, then utilize it in the renderCell attribute of the column.

Here's an illustrative example:

// Custom component for button and modal rendering
const ButtonAndModal = ({ row }) => {
  const [open, setOpen] = React.useState(false);

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };
  return (
    <>
      <Button onClick={handleOpen}>{row.action}</Button>
      <BasicModal
        open={open}
        onOpen={handleOpen}
        onClose={handleClose}
        row={row}
      />
    </>
  );
};

const columns = [
  { field: "id", hide: true },
  { field: "name", headerName: "Name", width: 150 },
  {
    field: "action",
    headerName: "Action",
    width: 150,
    renderCell: ButtonAndModal // Implement custom component here
  }
];

To view the complete demo, click here.

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

Choose a division of an element within an embedded frame

Two different pages on the same website, Home.html and Page2.html. Home.html contains the following code: <html> <iframe id="one" src="page2.html" style="display:none"></iframe> <div id="container"> <h1& ...

Attempting to compare the HTML datetime with the current time in order to implement conditional formatting

I am working with a SharePoint discussion list that includes a field named "Last Updated." My goal is to identify and highlight rows where the last update was more than 1 hour ago. Here is my current approach: <html> <head> <sc ...

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

I'm looking for the documentation for the latest version of Footable's Events. Can you point me

Does anyone know where to find information on the events that are fired for Footable and how to handle them? I checked the documentation at , but it doesn't provide much detail on events. If you have any resources or suggestions, please let me know! ...

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

Passing an event from a Vue3 parent component to its child component

How do I trigger a load event from a parent component to the child component? The child component needs to be able to listen for the load event in a slot-defined element and then perform some actions with the event. For example: <template> <slot ...

Experience the visually stunning React Charts line chart featuring grouped labels such as months and weeks

Can you create a line chart in recharts with grouped points, such as displaying 6 months data series per day for about 180 days? Each point on the chart represents a day, but I want the X-axis labels to show the corresponding month like Jan, Feb, Mar, Apr, ...

I want to use the enter key for posting, but also have the ability to use the shift and enter key to create a

$("#post_text").keydown(function(e){ // Checking if Enter key was pressed without shift key if (e.keyCode == 13) { // Prevent default behavior e.preventDefault(); } if (e.keyCode == 13 && !e.shiftKey) { alert('test'); } }); I a ...

Securing routes with server-side validation

I've been experimenting with different methods to secure a route for unauthenticated users, but I'm facing difficulties in implementing it effectively. One common issue I encountered while attempting authentication from getServerSideProps was th ...

The drag and drop functionality in React is not compatible with Material UI components

I attempted to create a draggable horizontal list of MUI buttons using react beautiful drag and drop, but unfortunately it doesn't seem to be functioning as expected. To achieve this, I enclosed my buttons within <DragDropContext>, <Droppabl ...

Retrieve information stored in a component's data variable

After creating a Vue repository using vue init webpack my-app My main.js file looks like this -- // The Vue build version to load with the import command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue fro ...

Do you have any suggestions on how to fix this npm SQLite installation issue?

Could use some help with an SQLite installation error I'm encountering. Any ideas on what the issue might be and how to resolve it? C:\Users\jacka\Downloads\discord-emoji-stealer-master\discord-emoji-stealer-master>npm i & ...

What is the best method for transferring states between components?

When it comes to React JS, I am a beginner looking to develop a ToDo list application. In my project, I have the main page App.js, where I created the component MainBlock. This MainBlock component structures the layout into left and right sides. On the rig ...

Node.js's module-only scope concept allows variables and functions defined within

Currently, I am attempting to create a function that can set a variable at the top-level scope of a module without it leaking into the global scope. Initially, I believed that implicit variable declarations within a module would remain confined to the modu ...

Angular directive dilemma

Angular is causing some issues for me as I am a beginner in using it. Below is the JSON data that I am dealing with: [ { "name":"43", "values":{ "audio":"Audio Only", "low":"Low Bandwidth", "medium":"Medium Bandw ...

Developing an uncomplicated Angular promise following the invocation of a service

Delving into the realm of Angular promises for the first time, I'm determined to grasp its concepts. In my MainController, I have a simple authentication process using myAuthSrv.authUser with a username and password. Upon successful authentication (. ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

npm unable to retrieve Meteor package

When I attempted to install meteorite using nodejs v0.10.22 and npm v1.3.14, the installation failed with the following error: $ npm install meteorite npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm ...

Is it best practice to initialize loaded scripts before the JQuery .load callback is called or should it be done after the .ready callback in the loaded script?

When I click a button in my main document, I load the content of a specific div using jQuery: $("#my_div").load(function() { alert("Content Loaded"); }); The loaded content contains a script: <script> alert("Initial Alert from External Script" ...