Our Reviews page automatically
displays all the reviews,
loading the data from the
available Markdown files.
But our Home page always displays
the same content,
because, in that page component,
we still have some hard-coded review data.
So, here's a little exercise for you:
change this component to load the
featured review automatically.
You can write a new function for that,
in the "reviews.js" file,
called "getFeaturedReview" for example.
This should return a single object,
with all the properties, like "title",
"body", and so on.
As the "featured" review we could pick the latest one,
based on the date.
So, the easiest way to do this is
modify the existing getReviews() function
to sort all the reviews by most recent first.
You can use the "sort" method
on the array to do that,
comparing the "date" property of each review.
At that point, getFeaturedReview
can simply call getReviews
and take the first element in the array.
This way the HomePage should automatically display
the latest review we published
as the "featured" one.
If you want to do this exercise,
stop this video, and start it
again once you're finished.
I'll show you my implementation
in about 3 seconds.
Ok, here's what I've done.
Let's start from "reviews.js".
In the "getReviews" function,
I've added a line to sort the "reviews"
before returning them.
This is using the "sort" method on the array,
which takes a "compare" function as argument,
that specifies how to sort the elements.
In this case, I'm comparing the "date"
property of the two review objects.
This way the Reviews page should also show
the most recent review first,
and the oldest one at the bottom.
Before this change, the order depended on
whatever the file system returned
to the "readdir" function.
Just to remind you,
the date for Hellblade is May 6th,
while, if we look at the Hollow Knight page,
this one is May 5th,
and, for Stardew Valley,
it's May 4th.
So you can see that the dates are
in reverse chronological order.
Also, since they're strings in the ISO format,
we can simply compare them alphabetically,
with "localeCompare".
If we were to compare review
"a" to review "b" by date,
then we'll see the oldest review at the top,
and the latest one at the bottom.
But we want the reverse order,
so we can compare "b" to "a" instead,
and they will be sorted with
the most recent first.
Anyway, let's go back to our Home page now.
Since getReviews returns the
data in the right order,
to get the latest review
we can simply take the first element in the array.
And that will be the featured review
that we show in the HomePage.
"review" will be an object,
with all the properties that
we then need to display
in the right places in the page elements.
And this way the HomePage will always display
the latest review automatically.