What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" feature instead of relying on the internalEditComponents provided by the library. Essentially, I have a customized dialog as shown below. When I check the values in the handle create function, they appear empty unless I use the internalEditComponents. How can I populate the values props in the handle create function without having to create extensive custom logic?

// handle create function

  const handleCreate: MRT_TableOptions<any>['onCreatingRowSave'] = props => {
    const { values, table, row } = props;

    console.log('handleDomainCorrectionCreate', values); // this is empty

  };

// custom dialog

   renderCreateRowDialogContent: props => {
       const { table, row, internalEditComponents } = props;
      <DialogTitle>Add correction entry</DialogTitle>
          <DialogContent>
            <Box sx={{ my: 2 }}>
              <DialogContentText variant="subtitle2">From</DialogContentText>
              <TextField
                autoFocus
                id="error_name"
                label="Error Name"
                type="text"
                fullWidth
                variant="standard"
                name="error_name"
                onChange={event => setErrorName(event.target.value)}
                value={errorName}
              />
            </Box>
            <Box sx={{ my: 2 }}>
              <DialogContentText variant="subtitle2">To</DialogContentText>
              <TextField
                id="corrected_name"
                label="Corrected Name"
                type="text"
                fullWidth
                variant="standard"
                name="corrected_name"
                onChange={event => setCorrectedName(event.target.value)}
                value={correctedName}
              />
            </Box>
          </DialogContent>
          <DialogActions>
            <MRT_EditActionButtons variant="text" table={table} row={row} />
          </DialogActions>
}

Answer №1

If you need assistance, take a look at the material-react-table V1 CRUD example below:

    const columns = useMemo<MRT_ColumnDef<IPmsProgress>[]>(
      () => [
        {
          ...
      ],
      [ validationErrors],
    );    
    
    // Manage state for inserting values
    const [values, setValues] = useState<any>(() =>
      columns.reduce((acc, column) => {
        acc[column.accessorKey ?? ''] = '';
        return acc;
      }, {} as any),
    );

    const handleCreateNewRow: MRT_TableOptions<IPmsProgress>['onCreatingRowSave'] = ({
      table,
    }) => {        
      const newValidationErrors = validatePmsProgress(values);
      if (Object.values(newValidationErrors).some((error) => error)) {
        setValidationErrors(newValidationErrors);
        return;
      } 
      const request: IRequestPmsProgress = {
        contractid: currentContractId,
        dateid: currentReportDateId,
        item: values.item,
        lastplanprogress: values.lastplanprogress,
        lastplanvirtualprogress: values.lastplanvirtualprogress,
      }
      setValidationErrors({});
      addPmsProgress(request);
      table.setCreatingRow(null); // Exit creating mode
    };
    
    ...
    const table = useMaterialReactTable({
      ...
      renderCreateRowDialogContent: ({ table, row }) => (  <>
          <DialogTitle variant="h6" fontFamily="sans serif" textAlign='center'>Add new item</DialogTitle>
          <DialogContent
            sx={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}
          >
            <form onSubmit={(e) => e.preventDefault()}>
              <Stack
                sx={{
                  width: '100%',
                  minWidth: { xs: '300px', sm: '360px', md: '400px' },
                  gap: '1.5rem',
                }}
              >
                {columns.filter(column => 
                    column.accessorKey === 'item' ||
                    column.accessorKey === 'lastplanprogress' || 
                    column.accessorKey === 'lastplanvirtualprogress').map((column) => (
                  <TextField
                    key={column.accessorKey}
                    variant='filled'
                    label={column.header}
                    name={column.accessorKey}
                    type={column.accessorKey === 'item' ? 'text' : 'number'}
                    onChange={(e) =>
                      setValues({ ...values, [e.target.name]: e.target.value })
                    }
                  />
                ))}
              </Stack>
            </form>
          </DialogContent>
          <DialogActions sx={{ p: '1.25rem' }}>
            <MRT_EditActionButtons variant="text" table={table} row={row}/>
          </DialogActions>                
        </>
      ),
      ...
    })
    ...

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

Arranging JSON information based on category

I am currently populating an HTML table with data retrieved from a JSON file. It currently displays all the data in the order it appears in the JSON file, but I would like to organize it into different tables based on the "group" category in the file such ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

Would you like to know how to implement a feature in React Router that allows you to load a specific number of

As a newcomer to react-router, I have been working on displaying JSON data from the public folder by using the slice function to show some of it. Now, I am facing difficulty in implementing the functionality to display more data when the "see more" butto ...

Using the Material UI picker in combination with Formik within a class component

I've integrated the @material-ui/pickers package with Formik in my React class component. However, when I attempt to adjust the date and time using the picker, I encounter the following error: TypeError: Cannot read property 'type' of unde ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Using jQuery to load content with a dynamic variable instead of specific element IDs

I am facing a minor jQuery issue. I am trying to load a specific area of an external HTML document into a div, but instead of loading just that particular area, the entire document is being loaded. Here's the code snippet for the trigger: $('a& ...

Is it possible to align divs so that they touch when they wrap to a new line, creating a grid-like appearance?

My React board component consists of an array of divs that I want to arrange in a grid-like map. The issue is, when the div wraps to a new line, there is significant space between each row. I aim to have the divs close together with no gaps. GameMap state ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

Next.js endeavors to interpret MDX files as basic JavaScript code

Currently, I'm in the process of creating a website using Next.js and incorporating (local) MDX files for my content. However, I've encountered an issue where whenever I add a .MDX file to my source tree and attempt to navigate to it, Next.js thr ...

Deriving worth from a JSON object

My JSON data structure has the following format: .... "location" : { "lat" : 37.42140090, "lng" : -122.08537010 }, .... I am having trouble accessing the lat and lng values. Any suggestions on how to do this? Cu ...

Next.js allows for passing dynamically loaded server-side data to all components for easy access

(I've recently started working with Next.js and inherited a project built using it, so please forgive me if this is something obvious that I'm missing) I have a set of data that needs to be loaded server-side on each request. Initially, I had im ...

Using jQuery to automatically scroll to the bottom of a div when sliding down

When a user clicks on a link to slide the div down, I want it to automatically scroll to the bottom of the div. I've attempted to use scrollTo and animate methods to achieve this effect. $('html, body').animate({ scrollTop: $("#elementID") ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

Updates to Providers in the latest release of Angular 2

When working with angular 2.0.0-rc.1, we implemented a Provider using the new Provider method as shown in the code snippet below: var constAccessor = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => EJDefaultValueAccessor), mul ...

Error occurred while attempting to run 'postMessage' on the 'Window' object within GoogleTagManager

Recently, I encountered an error stating "postMessage couldn't be cloned". This issue seems to be affecting most of the latest browsers such as Chrome 68, Firefox 61.0, IE11, and Edge. Error message: Failed to execute 'postMessage' on &ap ...

Attempting to extract a parameter from a URL and pass it as an argument to a function for the purpose of locating objects based on

I am trying to retrieve data from a URL http://localhost:3000/share/user=sampleuser to display objects with an author value that matches the one in the URL. However, I encountered an error when attempting to call a function that extracts the value from t ...

Adding a tooltip with a date format to a Highchart graph

Hey everyone, I'm currently working with a Highchart and I want to customize the tooltip value in a specific format. My categories and series are structured as follows: {"Categories":["2015-11-09","2015-11-08""2015-11-15"],"Series":[2,0,2]} Current ...

Handling OnClick events in D3 with Websocket Integration

My goal is to implement a Websocket in JavaScript that transmits a variable obtained when clicking on a node in a D3 chart. While I have made progress using static data, I'm struggling with initiating the code upon node click to retrieve the "user inf ...

what can prevent a React component from re-rendering?

Being a novice in the realm of React, I find myself with a perplexing query. Within my application, I have two distinct components - the parent component named Goals and its child, EditGoal. The Goals component functions to display all goals, while the Edi ...