Home > OS >  how to alternate rows based on odd/even index
how to alternate rows based on odd/even index

Time:03-20

I want to loop over data and show it in a bootstrap grid with an image on the left, text on right, then for the next iteration show the text on the left and image on the right etc. However, when using .map, I can only put the odd/even condition inside the column when I actually need it before.

      <Row className="align-items-center">
        {data.map((d, index) => (
          <Col md={6}>
            {index % 2 ? (
              <Image
                src={d.img}
                width={500}
                height={500}
              />
            ) : (
              <p>{d.title}</p>
            )}
          </Col>
        ))}
       </Row>

So, I guess it should look something like this if done manually

<Row>
    <Col md={6}>
        Image
    </Col>
    <Col md={6}>
        Text
    </Col>
    <Col md={6}>
        Text
    </Col>
    <Col md={6}>
        Image
    </Col>
</Row>

CodePudding user response:

You are displaying either of <Image> or <p> depending on the index. You should display both of them with their orders changed depending on the index

<Row className="align-items-center">
  {data.map((d, index) => (
      index % 2 ? (
        <>
          <Col md={6}>
            <Image
              src={d.img}
              width={500}
              height={500}
            />
          </Col>
          <Col md={6}>
            <p>{d.title}</p>
          </Col>
        </>
        ) : (
        <> 
          <Col md={6}>
            <p>{d.title}</p>
          </Col>
          <Col md={6}>
            <Image
              src={d.img}
              width={500}
              height={500}
            />
          </Col>
        </>
      ) 
  ))}
</Row>
  • Related