Use material-table in Next.js

Next.js and material-table are very easy to use and I use them a lot.
However, they don’t work well together, and material-table doesn’t work straightforwardly with Next.js.

There is a sticking point for using material-table in Next.js, and you will get the following error

  • TypeError: Cannot add property tableData, object is not extensible
  • material table Invariant failed: Draggable[id: 1]: Unable to find drag handle

In this article, we’ll take a look at some of the sticking points when using material-table in Next.js and how to fix them.

目次

Pass a new array for data in the material table

If you put json directly into the material-table in Next.js, you will get the following error.

Unhandled Runtime Error
TypeError: Cannot add property tableData, object is not extensible

To fix this error, you need to make a new array and pass it to material-table.
The following code will pass the data to the material-table.

import React, { useEffect, useState } from "react";
import MaterialTable from "material-table";

function table() {

    return (
        <>
            <MaterialTable
              data={JSON.parse(JSON.stringify(rows))}
              // or
              // data={rows.map(row => ({ ...row }))}
              ...
            />
        </>
    );
}
export default table;

After the window object is created, it is displayed in the material table.

This occurs because the DOM and window have not been loaded before the component is loaded.
This is why you get the following error

material table Invariant failed: Draggable[id: 1]: Unable to find drag handle

Even with this error, the tailble is still displayed.
However, behaviors such as onClick() for the delete icon will not fire.

To resolve this error, the window object must be ready before the table can be displayed.

import React, { useEffect, useState } from "react";
import MaterialTable from "material-table";

function table() {
    const [winReady, setwinReady] = useState(false);
    useEffect(() => {
        setwinReady(true);
    }, []);

    return (
        <>
            {winReady ? <MaterialTable ... /> : null}
        </>
    );
}
export default table;

Reference

https://stackoverflow.com/questions/59648434/material-table-typeerror-cannot-add-property-tabledata-object-is-not-extensibl

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする


reCaptcha の認証期間が終了しました。ページを再読み込みしてください。

目次