0

I am using React Bootstrap and trying to loop through content which is in two separate columns like this:

  <Container>
    <Row>
      {this.state.products.map(product => (
      <Col md={8}>
        <div className="title">{product.name}</div>
        <div className="desc">{product.description}</div>
      </Col>
      <Col md={4}>
        <div className="price">{product.price}</div>
      </Col>
      ))}
    </Row>
  </Container>

I have my closing tags so not sure why I a getting the error?

user8463989
  • 2,275
  • 4
  • 20
  • 48
  • Possible duplicate of [Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag](https://stackoverflow.com/questions/31284169/parse-error-adjacent-jsx-elements-must-be-wrapped-in-an-enclosing-tag) – Emile Bergeron Jul 17 '19 at 20:24

2 Answers2

2

The return of your map also needs to be wrapped in a containing tag, you can use React fragment tags <> https://reactjs.org/docs/fragments.html#short-syntax

<Container>
    <Row>
      {this.state.products.map(product => (
         <>
           <Col md={8}>
              <div className="title">{product.name}</div>
              <div className="desc">{product.description}</div>
           </Col>
          <Col md={4}>
            <div className="price">{product.price}</div>
          </Col>
      </>
      ))}
    </Row>
  </Container>
Cal Irvine
  • 1,104
  • 8
  • 17
1

Try this:

The problem is, your map on the products Array is returning two components of type Col, and React only accepts one returned element.

Explained here.

Also, <React.Fragment></React.Fragmint> Component Wrapper can also be written with this syntax: <></>

  <Container>
    <Row>
      {this.state.products.map(product => (
        <React.Fragment>
          <Col md={8}>
            <div className="title">{product.name}</div>
            <div className="desc">{product.description}</div>
          </Col>
          <Col md={4}>
            <div className="price">{product.price}</div>
          </Col>
        </React.Fragment>
      ))}
    </Row>
  </Container>
Sultan H.
  • 2,908
  • 2
  • 11
  • 23