Can someone please guide me on how to transfer information from a material ui datagrid Row to a form input?

I need assistance. I have a table that holds user data and I want to create a functionality where clicking on the edit button opens a dialogue box with a form pre-filled with the user's initial data. However, I'm currently only able to pass the user's id instead of the entire object.

Here is the link to view my full code on codesandbox.

User.js is the main file where I am encountering this issue.

import React, { useState, useEffect } from "react";
import { Button, Grid, Typography, Box } from "@material-ui/core";
import { DataGrid } from "@material-ui/data-grid";
import { useStyles } from "./UsersStyle";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";

const customerData = [
  { id: 1, name: "Customer 1", gender: "Male", email: "[email protected]" },
  { id: 2, name: "Customer 2", gender: "Male", email: "[email protected]" },
  { id: 3, name: "Customer 3", gender: "Female", email: "[email protected]" }
];

const Users = () => {
  const classes = useStyles();
  const [customers, setCustomers] = React.useState(customerData);
  const [editOpen, setEditOpen] = React.useState(false);
  const [name, setName] = React.useState("");
  const [gender, setGender] = React.useState("");
  const [email, setEmail] = React.useState("");
  let initialFormData = { id: null, name: "", gender: "", email: "" };
  const [currentCustomer, setCurrentCustomer] = React.useState(initialFormData);

  // initial data I am passing to customer state
  const columns = [
    { field: "id", headerName: "ID", width: 70 },
    { field: "name", headerName: "Name", width: 200 },
    {
      field: "gender",
      headerName: "Gender",
      width: 150
    },
    {
      field: "email",
      headerName: "Email",
      description: "This column has a value getter and is not sortable.",
      width: 250
    },
    {
      field: "action",
      headerName: "Action",
      width: 250,

      // Important: passing customers state so I can edit each user
      renderCell: (customers) => (
        <>
          <Button
            style={{
              backgroundColor: "#ffcc00",
              marginRight: 40,
              padding: "3px 35px"
            }}
            variant="contained"
            color="primary"
            type="submit"
            onClick={() => handleEditOpen(customers)}
          >
            Edit
          </Button>
          
          {/* when I click on edit button this dialogue will appear */}
          <Dialog
            disableBackdropClick
            open={editOpen}
            onClose={handleEditClose}
            aria-labelledby="form-dialog-title"
          >
            <DialogTitle id="form-dialog-title">Edit Customer</DialogTitle>

            {/* I want this form to have data of the user which has been clicked */}
            <form
              noValidate
              /* onSubmit={() => handleSubmit(id)} */
            >
              <DialogContent>
                <TextField
                  value={currentCustomer.name}
                  onChange={(event) => setName(event.target.value)}
                  autoFocus
                  margin="dense"
                  id="name"
                  label="Name"
                  type="text"
                  fullWidth
                />
                <TextField
                  value={currentCustomer.gender}
                  onChange={(event) => setGender(event.target.value)}
                  margin="dense"
                  id="gender"
                  label="Gender"
                  type="text"
                  fullWidth
                />
                <TextField
                  value={currentCustomer.email}
                  onChange={(event) => setEmail(event.target.value)}
                  margin="dense"
                  id="email"
                  label="Email Address"
                  type="email"
                  fullWidth
                />
              </DialogContent>
              <DialogActions>
                <Button onClick={handleEditClose} color="primary">
                  Cancel
                </Button>
                <Button onClick={handleEditClose} color="primary" type="submit">
                  Add
                </Button>
              </DialogActions>
            </form>
          </Dialog>
        </>
      )
    }
  ];

  const handleSubmit = (clickedUser) => {
    //some update will go
  };

  const handleEditOpen = (clickedUser) => {
    console.log(clickedUser);
    setEditOpen(true);
    setCurrentCustomer({
      id: clickedUser.id,
      name: clickedUser.name,
      gender: clickedUser.gender,
      email: clickedUser.email
    });
    console.log(currentCustomer);
  };

  const handleEditClose = () => {
    setEditOpen(false);
  };

  return (
    <div className={classes.customerList}>
      <DataGrid
        rows={customers}
        columns={columns}
        pageSize={5}
        checkboxSelection={false}
        disableSelectionOnClick={true}
      />
    </div>
  );
};

export default Users;

Answer №1

When you click the edit button, it doesn't just return the row object, but more than that. What you actually want is the data of the clicked row.

Instead of this:

 const handleEditOpen = (clickedUser) => {
    console.log(clickedUser);
    setEditOpen(true);
    setCurrentCustomer({
      id: clickedUser.id,
      name: clickedUser.name,
      gender: clickedUser.gender,
      email: clickedUser.email
    });
    console.log(currentCustomer);
  };

Use this instead:

 const handleEditOpen = (clickedUser) => {
    console.log(clickedUser);
    setEditOpen(true);
    setCurrentCustomer({
      id: clickedUser.row.id,
      name: clickedUser.row.name,
      gender: clickedUser.row.gender,
      email: clickedUser.row.email
    });
  };

Remember, after setting the state using setState, avoid using console.log to log the state because it is asynchronous and you can't guarantee that the state has already changed.

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

Improving form handling with Vuex: Ensuring state is only updated after pressing the submit button

I am currently working on developing a form that pulls data from a Vuex store, allowing users to update the form fields and then submit when they are ready. Most tutorials I have seen use v-model with computed get() and set() to retrieve values from the s ...

Java servlet, Selenium, and JavaScript are a powerful combination of tools that can

I am facing a situation where I need Selenium webdriver to be executed on the client side. On a webpage, I have a form with a Submit button inside it. The action attribute of the form calls a servlet named "servletName". Inside the servlet, the followin ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...

Unable to perform a default import in Angular 9 version

I made adjustments to tsconfig.json by adding the following properties: "esModuleInterop": true, "allowSyntheticDefaultImports": true, This was done in order to successfully import an npm package using import * as ms from "ms"; Despite these changes, I ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

Is there a way for me to access the source code of elements within React Native?

Currently, I am working on writing code using React Native and compiling it in Android Studio with an emulator. When I press ctrl+m on the emulator and select "show inspector" to click on elements, I am unable to see which line of code corresponds to the s ...

Automatically execute a function when the number input changes, but only if no further changes are detected after a certain period of time

I am implementing angularjs with an input field for numbers. I want to trigger an action automatically after a certain amount of time, but only if no further changes have been made to the number within that time frame (let's say 2 seconds). In my exa ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

Tips on obtaining the element that was used as the event selector

I am facing a challenge with a specific issue. Within a div containing various elements, I have implemented a mouseover event. The issue arises when trying to target this particular div in the mouseover function, as there are multiple automatically genera ...

Tips for showcasing a designated set of numbers in Vue Js while iterating?

Is there a way to specifically target numbers during a loop? For example, I only want to retrieve numbers 5 and above or within a certain range that I specify. <select name="" id="input" class="form-control" v-model="selectcompetitionyear"> < ...

Trouble encountered while making an axios.post call

Currently, I am in the process of developing a next.js project integrated with mongoose. As part of this project, I have implemented a login and register API for users. However, I have encountered an issue where when I pass the 'email' and ' ...

Is there a way to make a button on a single div only affect that specific div

I have a PHP query that echoes a div for each row in the table. I want the div to slide up and then, when the user clicks the "read more" button, the div slides down. However, since it is echoed in a loop, all the divs have the same IDs and classes. I wo ...

The jquery UI button is displaying too wide even though the padding is set to zero

My goal is to decrease the width of certain jQuery buttons. Though I have attempted to eliminate padding using the code below, there remains a minimum of 5 pixels on either side of the text within my button. .button().css({ 'padding-left':' ...

What is the best way to send the selected option from a dropdown to a button click function within the controller?

I need to pass the selected value from a user's country selection dropdown to the ng-click="saveChanges()" function on the submit button. Is there a correct method for achieving this? I want to be able to access the user's selection from the dro ...

Clone all documents from a NodeJS mongoose collection and transfer them to a different server's database

I need assistance with migrating my database to a new server. My collection consists of approximately 410,000 documents, and I am looking to transfer them in batches of 100 to my new server that runs on mongodb. Below is the code I have written for this ...

What is the process for assigning variables to modules using RequireJS?

Is there a way to define variables for modules in RequireJS? In simpler terms, how can I achieve the equivalent of the following using RequireJS: var fs = require('fs'); var child_process = require('child_process'); I am looking to s ...

Exploring the options for accepting various file formats with Swal SweetAlert

Currently, I am using Swal Sweet Alert within my Vue.js application. I have successfully implemented code to allow image files, but now I am seeking assistance on how to extend this functionality to include multiple file types such as PDFs, PPTs, and Doc ...

Transforming the AngularJS $http GET method to OPTION and including custom headers

var users= $resource('http://myapp.herokuapp.com/users', {}); users.get(); The change in the HTTP GET method to OPTION occurred after implementing a header method. var users= $resource('http://myapp.herokuapp.com/users', {}, { get ...

The POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...