Gitesh
Gitesh

Reputation: 386

Using props in functional component

I am getting array in props which is props.logsInfo.logs and I want to use it according to the number of elements in array instead of hard coding it like props.logsInfo.logs[0]['id']. I want to use map.Logs array size can be more than one.I don't want to write one more cells: [ { key: 'cell-0', children: props.logsInfo.logs[1]['id'] },How can i achieve it??

import React from 'react';
import Table from 'terra-table';
const StripedTable = props => (
  <Table
    summaryId="striped-table"
    summary="This table displays striped rows."
    numberOfColumns={4}
    dividerStyle="horizontal"
    headerData={{
      cells: [
        { id: 'header-Id', key: 'id', children: 'Id' },
        { id: 'header-vendorId', key: 'vendorId', children: 'VendorId' },
        { id: 'header-userId', key: 'userId', children: 'UserId' },
        { id: 'header-payLoad', key: 'payLoad', children: 'PayLoad' },
      ],
    }}

    bodyData={[
      {
        rows: [
          {
            key: 'row-0',
            cells: [
              { key: 'cell-0', children: props.logsInfo.logs[0]['id'] },
              { key: 'cell-1', children: props.logsInfo.logs[0]['vendorId'] },
              { key: 'cell-2', children: props.logsInfo.logs[0]['userId'] },
              { key: 'cell-3', children: props.logsInfo.logs[0]['payLoad']},
            ],
          },
        ],
      },
    ]}
  />
);
export default StripedTable;

Upvotes: 0

Views: 50

Answers (1)

Felix Kling
Felix Kling

Reputation: 817128

Yes, you can use .map:

 bodyData={[
      {
        rows: props.logsInfo.logs.map(log => ({
          key: log.id,
          cells: [
            { key: 'cell-0', children: log.id },
            { key: 'cell-1', children: log.vendorId },
            { key: 'cell-2', children: log.userId },
            { key: 'cell-3', children: log.payLoad},
          ],
        }),
      },
    ]}

You can also do the same for cells if you keep an array with the field names around:

const fields = ['id', 'vendorId', 'userId', 'payLoad'];

// ...


 bodyData={[
      {
        rows: props.logsInfo.logs.map(log => ({
          key: log.id,
          cells: fields.map(field => ({key: field, children: log[field]})),
        }),
      },
    ]}

Upvotes: 1

Related Questions