简体   繁体   中英

Return multiple react components from a javascript function

I'm trying to build a table dynamically in React. The cells in the table will come from the dataset property on an incoming HTML object. The table will have two columns - the name of the attribute and the value of the attribute.

This function builds the outer table:

  buildDataList = () => (
    <Scroll>
      <Table isStriped key={this.claimCountLimitPerFin} >
        <Table.Header>
          <Table.HeaderCell content="Name" minWidth="medium" />
          <Table.HeaderCell content="Value" minWidth="medium" />
        </Table.Header>
        <Table.MultiSelectableRows // this is probably not necessary?
          maxSelectionCount={10}
        >
          {this.buildTableRows2()}

        </Table.MultiSelectableRows>
      </Table>
    </Scroll>
  );

This is the function that I'm calling to build the TableRows :

  buildTableRows2 = () => {
    Object.keys(this.props.dataset).forEach(datum => <Table.Row
      id={datum}
      key={`ROW_${datum}`}
    >
      {this.buildTextCell(datum)}
      {this.buildTextCell(this.props.dataset[datum])}
    </Table.Row>);
  }

I cannot figure out how to get buildTableRows2 to return all of the TableRow s! It isn't returning any, though I see that it is looping through all the attributes of dataset as I expect. I tried wrapping it in a React fragment, but that didn't work. I can't think of any other possible solutions. Any ideas?

Two problems in your code:

  • You are not returning anything from the buildTableRows2() function. You need to add a return keyword before Object.keys() inside buildTableRows2() function.
  • .forEach() method doesn't returns anything, you will need to use .map() method.

Change the buildTableRows2() function as shown below:

buildTableRows2 = () => {
    return Object.keys(this.props.dataset).map(datum => (
       <Table.Row
         id={datum}
         key={`ROW_${datum}`}
       >
         {this.buildTextCell(datum)}
         {this.buildTextCell(this.props.dataset[datum])}
       </Table.Row>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM