Search code examples
reactjsmui-datatable

How do I render an array of items inside column using MUI-Data-Tables?


I have list of texts that are to be displayed inside a data-table using the MUI-Data-Table component but i am facing this problem of displaying not a single item in the column but a list of items. I have an item called system. It contains an array of countries so I want to display that array inside only one column but i don't know how to do it.

this is my json :

systeme:{
          archived: 0
           id: 1
           nomSysteme: "Environnement Tn"
           systeme_country: Array(1)
                   {
                    0: {id: 1}
                   length: 1
                     }
        }

and this is how i customize my column because there is a certain pattern that i need to follow :

 {
    name: "titre",
    label: "Titre",
    options: {
        filter: true,
        sort: false,
    }
},
{

    name: "theme.systeme.systeme_country",
    label: "Countries",
    options: {
        filter: true,
        sort: false,

    }
},

For more explanation the option name must be the same as in the json and it renders only one object but the theme.systeme.system_country is an array of countries's ids that i want to display but it won't let me i didn't know how to customize my columns to do such a thing or if there is a trick that i can do to make it happen


Solution

  • You could provide a customBodyRender for the specified field. An example could be found here: https://github.com/gregnb/mui-datatables/blob/master/examples/component/index.js

    import React from "react";
    import ReactDOM from "react-dom";
    import "./styles.css";
    import MUIDataTable from "mui-datatables";
    
    function App() {
      const data = [{ user: "john", langs: ["en", "de", "fr"] }];
      const columns = [
        { name: "user" },
        {
          name: "langs",
          options: {
            customBodyRender: (value, tableMeta, updateValue) => (
              <div>{value.join(",")}</div>
            )
          }
        }
      ];
      return <MUIDataTable data={data} columns={columns} />;
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);