Intro
One of the more confusing but simple concepts I had to wrap my mind around when first working with Javascript and React was programmatically rendering "cards" that usually display some image, button and variable information. You can then make lists of these cards from information stored in an API or a local db.json file.
This is actually quite simple to do when using a powerful tool like React, once you know how to go about it. By the time I built a list of plant cards for a "Plantsy App", I had it mastered. This list had a search feature and could be added to by a controlled form but I won't go into those features today.
List of Plant Cards
Plant Card JSX Code
The plant card component took in a prop "plant" that contained info from a db.json file with id, name, image, and price keys from an array of objects. This info was fetched and then passed down the card component give it all it needed to render the way we wanted. It even had condimental rendering with an in/out of stock button.
Mapping the Plant Cards
Now for the part you came for - mapping the plant cards. The plant list component was passed a prop of "plants" which could be changed via filtering or adding to our list with a form. It is important to note that you need to create a key attribute for this mapping to work properly and it is bad practice to use an index variable. Our information came with ids but you could also use the plant (not plants) variable for this.
Put all of this inside a <ul>
or <ol>
element and viola! All of your cards are easily and programmatically rendered with ease.
React Lists and Keys
React has many guides on it features. I recommend you give there website a look if you are still iffy on the technical aspect of mapping lists.
Top comments (0)