Search code examples
reactjsmaterial-uimaterial-table

Using a function in Material-Table render property


I need to use a custom function in Material-Table column render property. The function gets called, I get printed on the console the expected results, however, the result would simply not render in the table. Here is the code:

import React from 'react';
import HraReferenceDataContext from '../context/hraReferenceData/hraReferenceDataContext';
import MaterialTable from 'material-table';

const EmployeeDetailsCompanyDocuments = ({ companyDocumentsData }) => {
    const hraReferenceDataContext = React.useContext(HraReferenceDataContext);
    const { companyDocumentTypes } = hraReferenceDataContext;

    const getDocumentTypeForRow = id => {
        companyDocumentTypes.forEach(type => {
            if (type.id === id) {
                console.log(type.name)
                return type.name;
            }
        });
    };

    const columnInfo = [
        {
            field: 'typeId',
            title: 'Type',
            render: rowData =>{ getDocumentTypeForRow(rowData.typeId)}, //here is the problem
        },
        { field: 'created', title: 'Created On' },

    ];

    return (
              <MaterialTable
                 columns={columnInfo}
                 data={companyDocumentsData}
                 title="Company Documents List"
               />   
    );
};

Solution

  • Returning inside forEach doesn't work.

    change this function

    const getDocumentTypeForRow = id => {
            companyDocumentTypes.forEach(type => {
                if (type.id === id) {
                    console.log(type.name)
                    return type.name;
                }
            });
        };
    

    to

    const getDocumentTypeForRow = id => {
      return companyDocumentTypes.find(type => type.id === id).name;
    };
    

    update

    change

    render: rowData =>{ getDocumentTypeForRow(rowData.typeId)},
    

    to

    render: rowData => getDocumentTypeForRow(rowData.typeId),
    

    because you should return the value that is returned from getDocumentTypeForRow.