7. Loading the Entire Product Registry¶
- This section will aid to highlight the beauty and power of the portable and modular nature of React components!
- You will now load all of the seeded products into the registry.
- Within the
<ProductRegistry>
component now instead of just loading the first product in the array iterate over the entire list. In order to do this you will leverage the internalmap
function of the JavaScript language.
Note
JavaScript’s map
function
array.map(function(currentValue, index, arr), func())
map
is a function that is accessible on every array object. This function essentially allows efficient iteration over all of the array components.
For example:
> const myArray = [1,2,3,4] > myArray.map(arrayItem => console.log(arrayItem)) 1 2 3 4
Instead of loading just the first product from the seed now iterate over all the products and define a
<Product>
component to be rendered for each:remember anything between
{}
allows you to use native JavaScriptreturn ( <div className='ui unstackable items'> { Seed.products.map(product => <Product title={product.title} description={product.description} submitterAvatarUrl={product.submitterAvatarUrl} productImageUrl={product.productImageUrl} /> ) } </div> );
Now you will notice an error in the browser console stating:
Warning: Each child in an array or iterator should have a unique "key" prop.
The use of the
key
prop is something that the React framework uses to identify each instance of the Product component.For the time being just remember that this attribute needs to be unique for each React component.
Add a
key
andid
prop to the<Product>
component:<Product key={'product-'+product.id} id={product.id} title={product.title} description={product.description} submitterAvatarUrl={product.submitterAvatarUrl} productImageUrl={product.productImageUrl} />
Resulting with the final
<ProductRegistry>
component:class ProductRegistry extends React.Component { render() { return ( <div className='ui unstackable items'> { Seed.products.map(product => <Product key={'product-'+product.id} id={product.id} title={product.title} description={product.description} submitterAvatarUrl={product.submitterAvatarUrl} productImageUrl={product.productImageUrl} /> ) } </div> ); } }
And all seeded products should be rendered!