I cant seem to get this simple function to work basically my markup is like so(simplified)
{ loading || Object.keys(product).length <= 0 ? \'loading\' :
JSX doesn't allow if statement
within the return function. But you are allowed to use ternary expressions
{ loading || Object.keys(product).length <= 0 ? 'loading' :
<div>
{(condition here)? <div>Hello World</div>: null}
<ProductPictureWidget mainPic={product.pic_url} />
<ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>
</div>
}
However if you want to make use of if statement
there is an alternative way to do it, i.e to call a function within which you use the if-else statements
conditionalRender() {
if(condition) {
return <div>Hello</div>
} else {
return null
}
}
{ loading || Object.keys(product).length <= 0 ? 'loading' :
<div>
{this.conditionalRender()}
<ProductPictureWidget mainPic={product.pic_url} />
<ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>
</div>
}
JSX only allows expressions, not statements. The ternary operator is an expression. if
starts an if statement. You can see why an if statement wouldn't work by looking at the compiled JavaScript (with the if statement removed):
{
loading || Object.keys(product).length <= 0 ? 'loading' : React.createElement(
'div',
null,
React.createElement(ProductPictureWidget, { mainPic: product.pic_url }),
React.createElement(ProductOptionsWidget, { product: product, activeProps: activeProps, selectProductOption: undefined.selectProductOption })
);
}
JSX amounts to function calls and object declarations. If the if
statement were compiled, it would yield invalid JavaScript:
{
loading || Object.keys(product).length <= 0 ? 'loading' : React.createElement(
'div',
null,
if(){ }, // This is **invalid** JavaScript!!
React.createElement(ProductPictureWidget, { mainPic: product.pic_url }),
React.createElement(ProductOptionsWidget, { product: product, activeProps: activeProps, selectProductOption: undefined.selectProductOption })
);
}