skip to Main Content

I just want to get the data of the row , so all the values of the columns when I click in the ‘pencil’ button. Example: What my table looks like for the first row I want to get in different atributes the email, id, etc. Everytime in the console.log I just get undefined.

Here is my code; Thank you


import React,{Component ,useContext,useMemo,useState,useEffect,forwardRef } from 'react';
import { UserContext } from '../providers/userContext';
import { ProductService } from '../services/productService';
import MaterialReactTable from 'material-react-table';
import Edit from '@material-ui/icons/Edit';
import IconButton from '@mui/material/IconButton';
import Box from '@mui/material/Box';
//import Box from '../props/box';
export default function TableUsers() {
  
  const { user } = useContext(UserContext);
  const { getAllUsers } = ProductService()
  const [tableData,setTableData ] = useState([{}]) 
  
  const tableIcons = {  Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />)}

  useEffect(() => {
    getAllUsers(user.token)
    .then((response) => {
      setTableData(response.users) ;  <- Here is where i get my data formControlClasses, a request to an api
    })
    .catch();
  }, []);
  
  //should be memoized or stable
  const columns = useMemo(
    () => [
      {
        accessorKey: 'email', //access nested data with dot notation
        header: 'EMAIL',
      },
      {
        accessorKey: 'id',
        header: 'ID',
      },
      {
        accessorKey: 'name', //normal accessorKey
        header: 'NAME',
      },
    ], [],
  );


  return <MaterialReactTable 
    icons={tableIcons}
    columns={columns} 
    data={tableData} 
    enableRowActions={true}
    renderRowActions={({ row, table }) => (
      <Box>
        <IconButton onClick={(e, data)=> console.log( data.email)}>  <- Problem here  
          <Edit />
        </IconButton>
      </Box>
    )}
    getRowId={(originalRow) => {}} 
  />;
}

I tried using the "row" prop, putting in the paramenters of the onClicked (e,row), (e, data) and it just shows undefined everytime.

2

Answers


  1. Chosen as BEST ANSWER

    The solution was "row.original.whatever" Thats how you get the values of the columns

    renderRowActions={({ row }) => (
      <Box>
        <IconButton onClick= {() => console.log( row.original.name)}>  
          <Edit />
        </IconButton>
      </Box>
    )}
    

  2. I have done this without useRef, since all the table data is coming from database of some JSON file and we can use all-of-it or some-of-it inside table, then we can map rows and during that map iteration, we can set values for each rows and perform any action/custom action.

    I am guessing rows is array containing data for table rows. I have full code since I just implemented it few days ago for one of my ongoing project. let me know if you want to look at full code.

    Edit function:

    const handleEdit = item => {
        console.log('Edit Mode On:', item) // YOU HAVE ALL DATA FOR CLICKED ROW, PERFORM ANY ACTIONS/VALIDATIONS YOU WANT HERE
      }
    

    Rows data for DataGrid:

    const tableRows = rows.map(item => {
            return {
              
              name: item.name, // AND ALL OTHER COLS OF YOUR CHOICES
              actions: (
                <Box sx={{ display: 'flex', justifyContent: 'space-between', gap: '1rem' }}>
                  <Fab
                    color='primary'
                    aria-label='edit'
                    size='small'
                    onClick={() => {
                      handleEdit(item)
                    }}  // HERE WE HAVE ALL DATA FOR ROW, WHY NOT SEND IT TO EDIT FUNTION, AND DO WHATEVER YOU WANT THERE.
                  >
                    <Icon icon='mdi:pencil-outline' />
                  </Fab>
                  
                </Box>
              )
            }
          })
        
    

    Cols for DataGrid:

    const columns = [
            { field: 'name', headerName: 'City', flex: 1, filterable: false },
            {
              field: 'actions',
              headerName: '',
              flex: 0.15,
              renderCell: params => params.value,
              filterable: false,
              sortable: false
            }
          ]
    

    and in jsx:

    return (
    <DataGrid
     // YOUR PROPS FOR DATAGRID
     autoHeight={true}
     sx={{ width: '100%' }}
     rows={tableRows}
     columns={columns} />
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search