aishcript
aishcript

Reputation: 563

How do I send data from material ui datagrid Row to form input?

Please help me. I have a table containing some user data, I want when a user clicks on the edit button my dialogue box should open with a form with the initial data of that user. But I'm not able to pass the entire object rather only the id of the user is passed.

Here is the link of my complete code on codesandbox.

User.js main file where I am having 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;

Upvotes: 1

Views: 4826

Answers (1)

Vinicius Katata
Vinicius Katata

Reputation: 1051

The click in the edit button doesn't return just the object of the row, it returns more than that. What do you want it's the data of the clicked row.

Replace 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);
  };

By, this:

 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 the setState you should never console.log the state, because it is async and you cant rely that state already changed

Upvotes: 1

Related Questions