Reusable React Table with break points

PHOTO EMBED

Thu Jul 29 2021 20:26:18 GMT+0000 (Coordinated Universal Time)

Saved by @stephanieraymos #javascript #react #table

import React from "react";
import PropTypes from "prop-types";

const Table = ({ tableData, headingColumns, title, breakOn = "medium", onItemClick, onHeadingClick, headingColumnFields }) => {
  let tableClass = "table-container__table";

  if (breakOn === "small") {
    tableClass += " table-container__table--break-sm";
  } else if (breakOn === "medium") {
    tableClass += " table-container__table--break-md";
  } else if (breakOn === "large") {
    tableClass += " table-container__table--break-lg";
  }

  const data = tableData.map((row, index) => {
    let rowData = [];
    let i = 0;

    for (const key in row) {
      rowData.push({
        key: headingColumns[i],
        val: row[key],
      });
      i++;
    }

    return (
      <tr key={index} onClick={()=>onItemClick(index)}>
        {rowData.map((data, index) => (
          <td key={index} data-heading={data.key}>
            {data.val}
          </td>
        ))}
      </tr>
    );
  });

  return (
    <div className="table-container">
      <div className="table-container__title">
        <h2>{title}</h2>
      </div>
      <table className={tableClass}>
        <thead>
          <tr>
            {headingColumns.map((col, index) => (
              <th key={index}  onClick={() => onHeadingClick(headingColumnFields[index])}>{col}</th>
            ))}
          </tr>
        </thead>
        <tbody>{data}</tbody>
      </table>
    </div>
  );
};

Table.propTypes = {
  tableData: PropTypes.arrayOf(PropTypes.object).isRequired,
  headingColumns: PropTypes.arrayOf(PropTypes.string).isRequired,
  title: PropTypes.string.isRequired,
  breakOn: PropTypes.oneOf(["small", "medium", "large"]),
  onItemClick: PropTypes.func.isRequired,
  onHeadingClick: PropTypes.func.isRequired,
  headingColumnFields: PropTypes.arrayOf(PropTypes.string).isRequired
};

export default Table;



// ------ USING THE TABLE -------
import Table from "./components/Table";
        {data ? (
          <Table
            tableData={data.results.sort(sortMovies).map((movie) => {
              return [
                data.title,
                new Date(data.release_date).toLocaleDateString(
                  undefined,
                  options
                ),
              ];
            })}
            headingColumns={["Title", "Release Date"]}
            title="Pixar Movies"
            breakOn="small"
            onItemClick={handleClick}
            onHeadingClick={handleSort}
            headingColumnFields={["title", "release_date"]}
          />
        ) : null}
content_copyCOPY

Uses SCSS for the breakpoints. Includes sort functionality and data clicking functionality to load said data details.