Home > front end >  React Dynamic append using map
React Dynamic append using map

Time:10-25

I am new to react,

I am learning react, In this process I tried to create a for loop render using react. Were I am stuck in the following code

Below is my code

  <Container>
            <Row xs={3} md={4} lg={6}>
            {[...Array(numberOfCards)].map((e, i) => {
                return (
                  <Col className='mt-5' key={i 1}> 
                      <Card >
                          {/* <Card.Img top width="100%" src="/images/companylogo.png" alt="Card image cap"/> */}
                          <Card.Body>
                              <Card.Title tag="h5">Card title</Card.Title>
                              <Card.Subtitle tag="h6" className="mb-2 text-muted">Card subtitle</Card.Subtitle>
                              <Card.Text>Some quick example text to build on the card title and make up the bulk of the
                                  card's
                                  content.</Card.Text>
                              <Button onClick={() =>addquantity({i 1},{email})}>Button</Button>
                          </Card.Body>
                      </Card>
                  </Col>
                )
            })}
            </Row>
        </Container>

here, In the Button Onclick event I am passing the "{i 1}"

enter image description here

Can you help me to understand what I am doing wrong here.

Thanks in advance

CodePudding user response:

When you are defining the function in the onClick, the variables are in scope and shouldn't be inserted using {...} formats.

This should work (note that email should be defined somewhere):

         <Container>
            <Row xs={3} md={4} lg={6}>
            {[...Array(numberOfCards)].map((e, i) => {
                return (
                  <Col className='mt-5' key={i 1}> 
                      <Card >
                          {/* <Card.Img top width="100%" src="/images/companylogo.png" alt="Card image cap"/> */}
                          <Card.Body>
                              <Card.Title tag="h5">Card title</Card.Title>
                              <Card.Subtitle tag="h6" className="mb-2 text-muted">Card subtitle</Card.Subtitle>
                              <Card.Text>Some quick example text to build on the card title and make up the bulk of the
                                  card's
                                  content.</Card.Text>
                              <Button onClick={() =>addquantity(i 1,email)}>Button</Button>
                          </Card.Body>
                      </Card>
                  </Col>
                )
            })}
            </Row>
        </Container>
  • Related