Skip to content

Instantly share code, notes, and snippets.

@c0urg3tt3
Last active November 4, 2017 03:15
Show Gist options
  • Save c0urg3tt3/4bb9d63194f0bb206d9b9506406d1d50 to your computer and use it in GitHub Desktop.
Save c0urg3tt3/4bb9d63194f0bb206d9b9506406d1d50 to your computer and use it in GitHub Desktop.
using return-array with react16
// https://jsfiddle.net/69z2wepo/90437/
....
const Section = ({children, products}) => (
<section>
{
// has products ?
products.length
// yes, map products
? products.map((product, index) => children({product, index}))
// no, set empty flag
: children({isEmpty: true})
}
</section>
)
....
const ProductList = ({insertAd, products}) => (
<Section products={products}>
{ // children as function
({isEmpty = false, product, index}) => {
// has empty flag ?
if (isEmpty) {
// return an empty message as no product has been provided
// only one child no need for a key
return <p>no product.</p>
}
// has product and index is greater than or equal to zero ?
if (product && (index >= 0)) {
// set productCard (do not forgot the key)
const productCard = <ProductCard key={product.id} product={product} />
// should insert ad ?
if (insertAd) {
// set ad (do not forgot the key)
const ad = <Ad key={`ad-${index}`} />
// return an array that contains productCard and ad
return [productCard, ad]
}
// return productCard only
return productCard
}
// the component is in an unexpected state
// return null, an informative message or debug the error maybe
return <p>something went wrong!</p>
}
}
</Section>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment