Zain763
Zain763

Reputation: 77

Getting unexpected token, expected "," while trying to map an array in React

So, this is what I'm doing inside of the return:

return (
    
    <React.Fragment>
      <Styles>
      <Container>
          <Row className="rows container">
          {results.length > 0 && (  
          {results.map(result => (
            
            <Col className="columns " xs={12} sm={6} md={4} lg={3} >
              <img src={result.poster_path}  alt="movie poster" />
              </Col>
              
          ))}
          )} 
              
          
        </Row>
        </Container>
        </Styles>
    </React.Fragment>
  )

But, it's giving me the error Unexpected token, expected "," . I don't understand, especially because I have used the same syntax in another component and that's not reporting any errors.

Upvotes: 0

Views: 597

Answers (1)

Twiggeh
Twiggeh

Reputation: 1160

Your return statement should look like this

return (
    <React.Fragment>
        <Styles>
            <Container>
                <Row className='rows container'>
                    {results.length > 0 &&
                        results.map(result => (
                            <Col className='columns ' xs={12} sm={6} md={4} lg={3}>
                                <img src={result.poster_path} alt='movie poster' />
                            </Col>
                        ))}
                </Row>
            </Container>
        </Styles>
    </React.Fragment>
)

(I removed the square brackets from around results.map)

Square brackets are used to inform jsx that you are going to execute javascript inside the jsx. You already started that execution on {results.length, if you add another pair of brackets inside the js execution block it will be perceived by js as you creating an object, hence the expected comma error.

Upvotes: 2

Related Questions