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 ponent only when cart
is not an empty array. However as soon as I use conditional rendering, I get the error "Unexpected token, expected ,". The mented 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?
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 ponent only when cart
is not an empty array. However as soon as I use conditional rendering, I get the error "Unexpected token, expected ,". The mented 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?
-
Could you try wrapping your logic in a
<div>
?return (<div> ... </div>)
– Grandas Commented Jun 30, 2017 at 4:13
1 Answer
Reset to default 8{}
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>
)