I'm currently mapping through an array of products in the render method returning list elements for each object, I want to create an html select tag for the quantity of products available. Only way I can think of doing this is by looping out an option for every quantity, but this seems to throw a syntax error when using it inside the map function.
I can't seem to find any questions regarding this, the whole loop inside of map function already returning jsx.
render() {
const products = this.props.products.map((product, id) =>
<li key={id} className='products-list-container' >
<div className='product-inner-div-wrapper'>
<div className='product-title-container'>
<p>{product.name}</p>
</div>
<div className='product-price-container'>
<p>{product.price.formatted_with_code}</p>
</div>
// THIS IS WHERE I TRY TO LOOP AND CREATE AN OPTION
// FOR EVERY QUANTITY
<select>
{
for (var i = 0; i < products.quantity; i++) {
return <option value={i}>{i}</option>
}
}
</select>
<div className='product-add-item-container'>
{ product.is.sold_out ? <p>SOLD OUT</p> :
<p onClick={() => this.addItem(product.id)}>add to cart</p>
}
</div>
<div className='products-image-container'>
<img src={product.media.source} />
</div>
</div>
</li>
);
return(
<div className='products-list-container'>
<ul className='products-list-ul'>
{products}
</ul>
</div>
)
}
Instead of creating a loop, you can use a map here as well, with some array trickery:
{new Array(product.quantity).fill().map((_, i) => <option>{i}</option>)}
It's not very pretty - but you can pull this out into its own function, and name it descriptively.
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.