0

I am working with Material-UI and getting data from the backend. There is no issue with the backend, but I don't know how to loop data and print it in a table format using Material-UI. Can anyone guide me on how to print data in a table format?

Here is my code so far:

import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { getProducts } from "../../services/products";
import MaterialTable, { MTableToolbar } from "material-table";

const productsList = props => {
  const [data, setData] = useState([]);
  const [state] = React.useState({
    columns: [
      { title: "Brand", field: "brand" }, //assume here my backend schema is brand
      { title: "Price", field: "price" }, //here price
      { title: "Model no", field: "model" } //here model
    ]
  });

  const getProducts = async () => {
    try {
      const res = await getProducts();
      setData(res.data);
      console.log(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getProducts();
  }, []);

  return (
    <MaterialTable
      components={{
        Toolbar: props => {
          return (
            <div>
              <MTableToolbar {...props} />
            </div>
          );
        }
      }}
      options={{
        actionsColumnIndex: 5,
        selection: true
      }}
    />
  );
};
export default function Company() {
  return <productsList />;
}

4
  • Does this answer your question? Looping through table data React JS Commented Jan 24, 2020 at 8:01
  • Hi @minus I have seen your link in that example, you are using bootstrap but in my scenario I am using Material ui so please tell me how to loop data in Material ui Commented Jan 24, 2020 at 8:05
  • Are you using the library material-table or the Table component from Material-UI? Commented Jan 24, 2020 at 8:12
  • I am using library material-tabel. Commented Jan 24, 2020 at 8:19

2 Answers 2

1

You have to set the data and columns value. So try it like this:

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

const fakeFetch = () => {
  return new Promise(resolve => {
    resolve({
      data: [
        { brand: "brand 1", price: 1, model: "123" },
        { brand: "brand 2", price: 1, model: "456" },
        { brand: "brand 3", price: 1, model: "789" }
      ]
    });
  });
};

export default function App() {
  const [data, setData] = useState([]);
  // When the columns don't change you don't need to hold it in state
  const columns = [
    { title: "Brand", field: "brand" }, //assume here my backend schema is brand
    { title: "Price", field: "price" }, //here price
    { title: "Model no", field: "model" } //here model
  ];

  const getProducts = async () => {
    try {
      const res = await fakeFetch();
      setData(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getProducts();
  }, []);

  return (
    <MaterialTable
      columns={columns}  // <-- Set the columns on the table
      data={data}        // <-- Set the data on the table
      components={{
        Toolbar: props => {
          return (
            <div>
              <MTableToolbar {...props} />
            </div>
          );
        }
      }}
      options={{
        actionsColumnIndex: 5,
        selection: true
      }}
    />
  );
}

To make it even easier you could also provide your fetch function (fakeFetch in this case) as the data value;

data={fakeFetch} // <-- Using this you wouldn't need the [data, setData], getProducts and useEffect code.

Working sandbox link

Sign up to request clarification or add additional context in comments.

Comments

0

As per the material-table approach, you have to put your whole fetched data on the data prop inside the MaterialTable component. So as far as I can understand, there is no looping made in this case by using the material-table library.

Assuming the attributes in your data object match the field names specified in your columns prop (if not, create an array of objects from your fetched data that matches the column fields or vice-versa).

And the code would be just the addition of the data prop in your table:

<MaterialTable
  // ... existing props
  data={data}
/>

Keep in mind that you could also use the remote data approach as described in the documentation which gives you the means to immediately query your data and fetch it inside the data prop of the table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.