0

I am writing a nested loop in React. All I am seeing is the final return statements of

tags. Where are the and going? Thank you.

{ this.state.data.headings.map( (heading, i) =>
    <h3 key={i}>{heading}</h3> &&
      // some headings do not have subheadings, tho
      // they still have statements. deal with these cases first...
      ((this.state.data.subheadings[i].length === 0 &&
        this.state.data.statements[i].map((statement, _j) =>
          <p key={i+_j}>{statement}</p>)) ||
        // cases where the group of statements has a subheading...
        (this.state.data.subheadings[i].map((subheading, j) =>
          <h4 key={i + j}>{subheading}</h4> &&
          this.state.data.statements[i][j].map((statement, k) =>
            <p key={i+j+k}>{statement}</p>))
        )
      )
    )
  }
listenlight
  • 654
  • 1
  • 12
  • 27

3 Answers3

1

A better way of doing this in my opinion is to separate this in different components each one of them taking care of one of the loops.in your case header,subheader,statement, etc.

Guillermo Quiros
  • 401
  • 3
  • 14
1

There is everything ok with you code, except you can refactor it to make more readable. Don't repeat yourself (DRY), always move duplicated code to separate component, in your example it is statement element. Also, i remove redundant key props.

render() {
    const {headings, subheadings, statements} = this.state;

    return headings.map((heading, i) =>
        <div key={i}>
            <h3>{heading}</h3>
            {
                subheadings[i].length
                    ? subheadings[i].map((subheading, j) =>
                        <div key={j}>
                            <h4>{subheading}</h4>
                            <Statements statements={statements[i][j]}/>
                        </div>
                    )
                    : <Statements statements={statements[i]}/>
            }
        </div>
    );
}

const Statements = ({statements}) => (
    statements.map((statement, i) =>
        <p key={i}>{statement}</p>
    )
);
Igor Alemasow
  • 4,484
  • 2
  • 27
  • 24
0

(omg folks,) feels like i had to take a picture to prove it...

solution, special thanks to a similar Q&A (I'm using React v15 out of an older template for Ether dApps)

{ headings.map( (heading, i) =>
      [ <h3 key={i}>{heading}</h3>,
        subheadings[i].length === 0 ?
          statements[i][0].map( (statement, j) =>
            <p key={j}>{statement}</p>,
          ) :
        subheadings[i].map( (subheading, j) => (
          [<h4 key={j}>{subheading}</h4>,
          statements[i][j].map( (statement, k) =>
            <p key={k} style={{color: 'green'}}>{statement}</p> )
          ]
        ))
      ])
}

screenshot of editor and browser

listenlight
  • 654
  • 1
  • 12
  • 27