1

I'm using DataGrid from MUI, it does have a checkbox function and I want to use it so that when I check it it adds the row data to a variable (the id, name, etc etc) so I can use it somewhere else with useLocation but it doesn't seem to be working ? I did a small test just to see if it was doing anything but it doesn't even show the console.log there's what I try:

.........

const [studentsID, setStudentsID] = useState([]);
  function currentlySelected(estudiantes) {
    setStudentsID(estudiantes)
    console.log(studentsID)
  }

...........

<DataGrid
        rows={estudiantes}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
        checkboxSelection
        onSelectionChange={currentlySelected}
        components={{
          Toolbar: CustomToolbar,
        }}
        
      />

All I want to do is to be able to send data to another page so I can work with the uid of the data and grab internal values such as (name, lastname) and that sort of thing let me know if you require anything else, any help/tips/documentation is welcome.

UPDATED This is my whole code in case you need it:

import React, { useState, useEffect, Fragment } from 'react'
import {db} from './firebase';
import { useHistory, useLocation } from 'react-router-dom';
import "./ListadoEstudiantes.css"
import * as locales from '@mui/material/locale';
import { DataGrid, 
  GridToolbarContainer, 
  GridToolbarColumnsButton, 
  GridToolbarFilterButton, 
  GridToolbarExport, 
  GridToolbarDensitySelector } from '@mui/x-data-grid';
import { Button, Container } from "@material-ui/core";
import PersonAddIcon from '@mui/icons-material/PersonAddSharp';
import { Box } from '@mui/system';

function ListadoEstudiantes({user}) {

  const history = useHistory("");
  const crearEstudiante = () => {
    history.push("/Crear_Estudiante");
  };

 const [estudiantes, setEstudiantes] = useState([]);
 const estudiantesRef = db.collection("usuarios").doc(user.uid).collection("estudiantes")

 useEffect(() => {
  estudiantesRef.onSnapshot(snapshot => {
    const tempData = [];
    snapshot.forEach((doc) => {
      const data = doc.data();
      tempData.push(data);
    });
    setEstudiantes(tempData);
  })
 }, []);

 function CustomToolbar() {
  return (
    <GridToolbarContainer>
      <GridToolbarFilterButton />
      <GridToolbarDensitySelector />
    </GridToolbarContainer>
  );
}

const columns = [
  { field: 'id', headerName: 'ID', width: 100 },

  {field: 'nombre', headerName: 'Nombre', width: 200},

  {field: 'colegio', headerName: 'Colegio', width: 250},

  {field: 'grado', headerName: 'Grado', width: 150}
]

    return (
      <Container fixed>
      <Box mb={5} pt={2} sx={{textAlign:'center'}}>
      <Button
      startIcon = {<PersonAddIcon />} 
      variant = "contained" 
      color = "primary" 
      size = "medium" 
      onClick={crearEstudiante} >
      Crear Estudiantes
      </Button>
      <Box pl={25} pt={2} sx={{height: '390px', width: "800px", textAlign:'center'}}>
      <DataGrid
        rows={estudiantes}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}

        components={{
          Toolbar: CustomToolbar,
        }}

        checkboxSelection
        onSelectionModelChange={(id) => {
          const selectedIDs = new Set(id);
          const selectedRowData = estudiantes.filter((row) =>
            selectedIDs.has(row.id.toString())
          );
          console.log(selectedRowData, selectedIDs );
        }}
        {...estudiantes}
        
      />
      </Box></Box></Container>
    )
}

export default ListadoEstudiantes

UPDATE No longers grants me an error but it doesn't seem to be saving the data

enter image description here

ReactPotato
  • 1,262
  • 3
  • 26
  • 46
  • 1
    Does [my other](https://stackoverflow.com/a/66424840/9449426) answer help you? `onSelectionChange` does not exist in the latest version of `DataGrid`. – NearHuscarl Sep 30 '21 at 03:30
  • I'll check it assap – ReactPotato Sep 30 '21 at 04:20
  • Can you show the error message? what's the version of `@mui/x-data-grid` are you using? – NearHuscarl Sep 30 '21 at 04:58
  • Alright this is EXACTLY what I want but I get an error on `const selectedRowData = rows.filter` it says row is not define @NearHuscarl – ReactPotato Sep 30 '21 at 05:39
  • I uploaded the error I get so you can visualize it better @NearHuscarl – ReactPotato Sep 30 '21 at 05:41
  • The `rows` is a specific variable from the other answer code, you should change to `estudiantes` – NearHuscarl Sep 30 '21 at 05:44
  • Oh that makes sense I didn't find any rows variable in the example so got confused, it doesn't crash anymore but is returning an empty string, however is not bringing the data for some reason, attached image – ReactPotato Sep 30 '21 at 05:52
  • I just updated the the `@mui/x-data-grid` to the latest version and it works [fine](https://codesandbox.io/s/66424752-get-row-item-on-checkbox-selection-in-react-material-ui-data-grid-forked-t9rvm?file=/demo.tsx). Did you install the next version as recommended [here](https://mui.com/components/data-grid/getting-started/#installation)? I also want to see the value of `estudiantes` – NearHuscarl Sep 30 '21 at 06:00
  • Yeah, I decided to reinstall it again and now is complaining: `./node_modules/@mui/x-data-grid/index-esm.js Module not found: Can't resolve '@mui/styles' in 'C:\React\venta_de_libros\node_modules\@mui\x-data-grid'` I'll check it tomorrow i'm falling sleep 1am here thanks for the help though – ReactPotato Sep 30 '21 at 06:06
  • Install all required packages. For reference, see [this](https://codesandbox.io/s/66424752-get-row-item-on-checkbox-selection-in-react-material-ui-data-grid-forked-t9rvm?file=/package.json) package.json – NearHuscarl Sep 30 '21 at 06:07
  • 1
    Oh yes found the missing one, sorry about that. Is working! yay oh man you have no idea the save you just gave me I can now sleep in peace I been trying to make it work the whole day but for some reason there are not many tutorials about DataGrid and parsing data using the checkbox, if you have ANY resource let me know man. Really appreciate it – ReactPotato Sep 30 '21 at 06:17
  • Also @NearHuscarl if by any chance you know the answer to this: [How to delete rows with select Checkbox](https://stackoverflow.com/questions/69384072/how-to-delete-multiple-rows-with-select-checkboxes-from-material-ui-data-grid-re) I'll appreciate it – ReactPotato Sep 30 '21 at 06:23
  • 1
    I mostly read [docs](https://mui.com/components/data-grid/), or search in the API [section](https://mui.com/api/data-grid/data-grid/), and read the discussion on github issues. To answer a lot of questions on here, I also need to read the [source code](https://github.dev/mui-org/material-ui) to learn more about how it works and provide concrete evidences (sometimes I'm still wrong tho). Remember that it took me a while to get here, I didn't just wake up and know how to answer your question immediately. It's just a lot of practice over a long period of time. – NearHuscarl Sep 30 '21 at 07:02
  • I see I just started not only to try and learn to code in React JS but to use this library I finished the whole code but it was ugly looking so I started to learn about MUI and I'm slowly migrating to it. – ReactPotato Sep 30 '21 at 14:33

0 Answers0