This is my code:
'use strict'
import React from 'react'
import { connect } from 'react-redux'
import { Panel, Col, Row, Well, Button } from 'react-bootstrap'
const Cart = ({ cart }) => {
const cartItemsList = cart.map(cartArr => (
<Panel key={cartArr.id}>
<Row>
<Col xs={12} sm={4}>
<h6>{cartArr.title}</h6>
</Col>
</Row>
</Panel>
));
return (
{ cart[0] &&
(<Panel header="Cart" bsStyle="primary">
{cartItemsList}
</Panel>)
}
{ !cart[0] &&
(<div></div>)
}
// {
// cart[0] ? (<Panel header="cart" bsStyle="primary">{cartItemsList}</Panel>) : (<div></div>);
// }
)
}
const mapStateToProps = state => ({
cart: state.cart.cart
})
export default connect(mapStateToProps)(Cart)
As you can see, I'm trying to render cartItemsList
nested inside a bootstrap panel component only when cart
is not an empty array. However as soon as I use conditional rendering, I get the error "Unexpected token, expected ,". The commented out line of code is the alternative I tried and that gives me the same error. If I get rid of the condition and just render the panel with cartItemsList
, it renders without any problems. It's only when I add the condition that I see this error. I was wondering what is causing this error to occur?
{}
is required to put the js expressions inside JSX
, here it is not required.
Write it like this without {}
:
return (
cart && cart.length ?
<Panel header="Cart" bsStyle="primary">
{cartItemsList}
</Panel>
:
<div>
</div>
)
Another way of writing same code is:
if(cart && cart.length)
return(
<Panel header="Cart" bsStyle="primary">
{cartItemsList}
</Panel>
)
return(
<div>
</div>
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.