Commit28 //JS React [Rendering Array Data Models]
I am studying JavaScript React with @skillcrush, in this module we will cover rendering array data models
I am learning with Skillcrush. Please check them out and consider signing up if you're looking to break into tech! Receive $250 off your course by using the link above. Use the coupon code: TWIXMIXY
NOTE: this discount is for Break Into Tech + Get Hired package exclusively. It's the same program I am participating in!
👾 Greetings travelers! We are diving back into our JS React course with Skillcrush. My spouse gets home from a week long camping trip tonight, so I spent most of the day tidying up and cleaning the house. I love the feeling of coming home to a clean and ordered house. So it brings me joy to share that with someone, especially after they have endured what I’m sure was a difficult week!
I’m skipping doing a JavaScript30 challenge today to just work on my bootcamp courses because I want to make sure I’m steadily progressing with my various learning intentions. I’d like to be doing 2 or even more modules of my React course each week. I may just even dive back in to full time bootcamp work for the next couple weeks because I have 9 more modules to go and my intention is to finish this before the end of May. 🤞
Array Data Models
How to render a list of elements
Build an array
Create a callback function
Map over your array with your callback function
Assign a unique key prop for each list element
Use the variable holding your mapped array
CALLBACK FUNCTION
when one function (aka the callback function), is passed into another function (aka the higher-order function)
MAP OVER AN ARRAY
to read the array & return a new array using the original array’s data
KEY PROP
used to identify each element in a callback function, giving each element a unique ID
Working with Array Data Models
Build An Array
// start with data model for the information to be displayed
const chargesData = [
{ name: "mint tea", price: 4.32, id: "0019" },
{ name: "tagine", price: 9.32, id: "0001" },
{ name: "gelato", price: 3.61, id: "0003" },
];
In this example array we are listing different potential charges at a restaurant.
Create A Callback Function
// callback function for rendering each item on the receipt
const renderItem = (charge) => (
<p>
<span> {charge.name}: </span>
<span> ${charge.price} </span>
</p>
);
This callback function, renderItem
, handles a single charge object at a time which will pull from our chargesData
array.
Map Over Your Array
// component for rendering the receipt
const Receipt = props => {
const receiptItems = props.charges.map(renderItem);
return <div>{receiptItems}</div>;
};
When mapping over an array it is first reading an array and then returning a new array created from the data in the original array. In this map array we will read the chargesData
array and pass each value to the renderItem
callback function. It then produces a new array from the values returned by our callback function.
Assign A Key Prop For Each List Item
Unique identifiers! Having previously worked at a company based in data management, this is the exciting part for me. How do I determine which set of values should be returned from the array? That’s down to the key prop!
const renderItem = charge => (
<p key={charge.id}>
<span> {charge.name}: </span>
<span> ${charge.price} </span>
</p>
Notice we added key={charge.id}
to the paragraph element.
The key prop is a unique ID used to identify each JSX element in the list of JSX elements returned by mapping over the array of data.
Each key prop must always be unique. This is assigned for each item at the top-level element, like the <p>
tag.
Use The Variable Holding Your Mapped Array
ReactDOM.render(
<Receipt charges={chargesData} />,
document.getElementById("root")
);
The way they explain this is that you would create a Receipt
component to tell React that you want to use the chargesData
array as the value for its charges
prop.
I still don’t full grasp this aspect of it, so I’m trusting the process and we will do some challenges to hopefully get it to set in my mind.
Build an Unordered List Using A Data Model
Time for our first challenge!
To begin we needed to export our data, so that we can connect it to our app.
export const filterData
We did this by adding export
in front of const filterData
.
export default filterData;
Initially I had typed it out as a separate statement, before I saw this simplified version in the solution code.
Next we imported our data into the app.
import { filterData } from "./data.js";
Originally I did not place the curly braces around filterData
and it seemed to work fine that way as well.
Finally we need to display the filter by data.
<FiltersList filters={filterData} />
I wasn't sure how to accomplish step 5. From reviewing previous challenges, I thought I maybe should have placed "filters" within the parenthesis and then use JSX to write out the objects.
const App = (filters) => (
<div className="App">{
/* TODO: pass your data model as a prop to your FiltersList component */}
<FiltersList ??? />
</div>
);
Obviously this wasn’t it. So sending it to my TA to help me clarify.
Once all the parts connected, I added a few more objects to the array.
That’s it for this challenge!
Render Our Data Model
On to our second challenge!
They gave us a code-along video for this. SO BRB and I’ll try to explain what we did after!
Hotels/index.js
import React from "react";
import Hotel from "./Hotel";
const renderHotel = (hotel) => <Hotel key={hotel.id} hotel={hotel} />;
const HotelsList = (props) => {
if (!props.hotels) {
return null;
}
const hotelListElements = props.hotels.map(renderHotel);
return <ul className="hotels-list">{hotelListElements}</ul>;
};
export default HotelsList;
In this challenge our goal was to get the hotel data to display.
To start we brought in the hotel.js file.
import Hotel from "./Hotel";
Then we created a variable called renderHotel. This was basically where I was halted and went to the code-along video.
const renderHotel = (hotel) => <Hotel key={hotel.id} hotel={hotel} />;
It just looks a bit chaotic to me. Maybe it’s because we’re using the word “hotel” so much that it’s confusing me. What I can see is that we are using a prop key, so to me this means we are pulling in hotel properties specifically so we can eventually display their values when we run it through the callback function.
const hotelListElements = props.hotels.map(renderHotel);
return <ul className="hotels-list">{hotelListElements}</ul>;
Then we are declaring a variable so we can map over the array of the renderHotel
data. Finally we are returning that data and new variable to display within an unordered list.
If I’m not making sense… that doesn’t mean you don’t understand it. Most likely it means *I* do not understand it. Learning! 😅
So yeah, that’s really all we did to get the data to display on the page.
Build a Data Model
Last challenge! and praise all that is good… another code-along video. I’ll see how much I can do first before resorting to it though.
Returning to the name tag generator from the last module.
We begin by creating a data file to house all the individuals. To me this signifies that at some point this data.js file could collect data from user entry or something. But maybe it doesn’t quite work like that.
So we created data.js
We created an array of all the nametags we want to generate. We set the array to export.
Next we imported the new data file into index.js
import { nameData } from "./data";
We then created a variable to render the names in the index.js file.
const renderNameTag = (name) => <NameTag name={name.name} key={name.id} />;
We then created our map array to run the render through in our callback function.
const NameTagElements = nameData.map(renderNameTag);
Finally we updated our return to display the data on the UI.
const App = () => {
const NameTagElements = nameData.map(renderNameTag);
return (
<div className="App">
<h1>Name Tag Generator</h1>
{NameTagElements}
</div>
);
};
Here is all of the index.js code in it’s totality.
import React from "react";
import ReactDOM from "react-dom";
import NameTag from "./NameTag.js";
import { nameData } from "./data";
import "./styles.css";
const renderNameTag = (name) => <NameTag name={name.name} key={name.id} />;
const App = () => {
const NameTagElements = nameData.map(renderNameTag);
return (
<div className="App">
<h1>Name Tag Generator</h1>
{NameTagElements}
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
And now I can go back to the data.js file and add as many objects as I may want and they will render on the website.
I’m not sure how to further explain what we did. I think it will take several more practice challenges like this for me to grasp fully what I’m doing, but it’s beginning to come together.
Quiz: Building and Rendering Data Models
Quiz time *dun dun dun*
This was a bit more tough for me. There were at least 3 I knew I didn’t know, and yup, definitely got those wrong & more!
Question #1: A callback function is a _______ that is passed into another _______ as an argument.
INCORRECT
Your Answer: map, array
Correct Answer: function, function
Love the use of repetitive “function” - that’s not confusing at all!!
Question #5: The last step to render an array data model is to use the variable holding:
INCORRECT
Your Answer: None of the above
Correct Answer: Your array of JSX elements
This was my instinct to guess, but I wasn’t sure.
Question #6: The function that a callback function gets passed to is called the:
INCORRECT
Your Answer: Out limits function
Correct Answer: Higher-order function
I literally do not remember these being discussed.
Question #7: The react code you write to render a data model can easily be used to render different:
INCORRECT
Your Answer: Functional components
Correct Answer: Data
I guess this makes sense, but any of the options probably would have for me. Still learning!
I’d love to hear your thoughts on this subject matter. How can I better familiarize myself with this? Any challenges you recommend? Please tell me in the comments!