List Rendering in React Js
Rendering JSX elements stored in variables
I have been studying React Js this past week and it has been surprisingly quite simple (so far) but one if my key takeaways from today's content has been how you can render JSX elements that have been stored in arrays/elements to the DOM. This was quite new to me and I could't quite understand how this was possible so I will make a walk-through of how it works.
Map functions
When presented with an array, more than often you may want to render that data to the DOM. We can use an example of a website that posts various articles on React Js topics.
posts: [
{
id: 1,
title: "Components 101",
date: "December 15, 2020",
preview: "Setting up the building blocks of your site",
minutes: 5,
},
{
id: 2,
title: "React Data Flow",
date: "December 11, 2020",
preview: "Passing props is never passé",
minutes: 15,
}
]
In this example, we will loop through the array and display the data inside an array element with the title as a header, the date in a small element and preview in a p element. We have a component called Article list which will pass on the data to an Article component which will place the data into the select elements.
In the ArticleList component, we have imported the Article element.
function ArticleList({ posts }) {
const article = posts.map((post) => {
const { id, title, date, preview, minutes } = post;
return (
<Article
key={id}
title={title}
date={date}
preview={preview}
minutes={minutes}
/>
}
}
We map through the items in posts and destructure individual posts into the id, title, date, preview and minutes variables. The data from the mapping of the posts is stored in the 'article' variable (we'll check on that later). We then pass it on to the Article component to handle setting the data into elements.
function Article({ title, date = "January 1, 1970", preview, minutes }) {
return (
<article>
<h3>{title}</h3>
<small>{date}</small>
<p>{preview}</p>
</article>
);
}
In the above segment, we import the props from the ArticleList component and set the default value for date. We then set the corresponding elements. From this function, everything in the return value is stored into the 'article' variable in the 'ArticleList' component.
Here is how it looks like in the console.
From here we can return the article variable inside whichever element you like.
function ArticleList({ posts }) {
const article = posts.map((post) => {
const { id, title, date, preview, minutes } = post;
return (
<Article
key={id}
title={title}
date={date}
preview={preview}
minutes={minutes}
/>
}
return <main> {article} </main>;
}
React automatically iterates through the 'article' array and renders each 'article' element individually.