Last active
November 4, 2017 03:15
-
-
Save c0urg3tt3/4bb9d63194f0bb206d9b9506406d1d50 to your computer and use it in GitHub Desktop.
using return-array with react16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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