jbreslow
jbreslow

Reputation: 314

Show boolean value in dynamically generated datatable columns

I am using PrimeReact Datatables and creating the columns dynamically from JSON. How do I render Boolean values in the table? Right now they are not showing up.

JSON Person Example

const person = [
   {
      "id":1,
      "person":"John Smith",
      "canEdit":false,
      "canView":true
   },
   {
      "id":2,
      "person":"Frank Jones",
      "canEdit":true,
      "canView":true
   }
]

Component

...
const dynamicColumns = columns.map((col,i) => {
    return <Column key={col.field} field={col.field} header={col.header} />;
});

return (
    <DataTable value={person}>
        {dynamicColumns}
    </DataTable>
)
...

Upvotes: 1

Views: 1249

Answers (1)

Iman Rabbi
Iman Rabbi

Reputation: 291

Use DataTable templating

  const booleanChecker = (rowData, item) => {
    if (typeof rowData[item.field] === "boolean") {
      return rowData[item.field] ? "Accepted" : "Unaccepted";
    } else {
      return rowData[item.field];
    }
  };

  const dynamicColumns = columns.map((col, i) => {
    return (
      <Column
        key={col.field}
        field={col.field}
        header={col.header}
        body={booleanChecker}
      />
    );
  });

  return (
    <div>
      <div className="card">
        <DataTable value={products}>{dynamicColumns}</DataTable>
      </div>
    </div>
  );

Upvotes: 3

Related Questions