Search code examples
javascriptreactjsextreact

React.js How to loop and render component inside component?


I'm trying to render components according to the data list. The data list include a list of address and records, in each address records, it contains one or multiple member records. The data structure looks like this:

combineData:[
addressData:{addressNo:... },
 memberDataList:[{...}]  
]

I want to render like this:

<address1>
<member1 of address 1>
<member2 of address 1>
<address2>
<member1 of address 2>
<member2 of address 2>
<member3 of address 2>
......
 
class AddressMembersTable extends React.Component {
    addressMembersViews = () => this.props.combineData.map((combineData, index) => {
        return (
            <Container layout="vbox">
                <AddressField
                    ref={'addressField'}
                    key={'addressField'}
                    addressData={combineData.addressData}
                />
  {combineData.memberDataList.forEach((memberData,index)=>{
               return(
                    <MemberField
                    ref={'memberField_' + index}
                   memberData = {combineData.memberDataList}
                   />
               )
        })}
        </Container>
        )

})}

I tried to loop the memberDataList for the MemberField components, but only AddressField is able to show. How can i render the components correctly?


Solution

  • You will map it the say way you did this.props.combineData. Array.prototype.forEach is a void return. You need to return the array of JSX you mapped to.

    {combineData.memberDataList.map((memberData, index) => (
      <MemberField
        key={index}
        ref={'memberField_' + index}
        memberData = {combineData.memberDataList}
      />
    ))}