Skip to content
Advertisement

I am trying to make my program list blog posts in order by the number of likes each blog has

I am currently working on a blog website and I want to list out the blogs in ascending order based on the amount of likes each blog has. However, whenever I run my current code, whenever I click “view” for one post, all of the post expand when I only want one of the post to expand, furthermore, whenever I hit “like” a like is left on all posts rather than just the one I left i like on.

Here is my code in App.js:

JavaScript

Finally, here is my code that deals specifically with each blog:

JavaScript

Advertisement

Answer

The mistake you did here is you created Blog.js(or whatever name you gave to the source file), you are treating it as an individual blog, and expecting ‘blogLikes` to work for an individual blog.

What structure needs to be. list-item


Create separate components for list and item and include list component into the app. The quick fix will be,

App.js

JavaScript

BlogList.js

To sort blogs by likes you apply Array.sort() before mapping.

JavaScript

Blog.js

JavaScript

Since you have a separate state for likes here in the Blog component its action or data won’t affect other blog components.


[update] If you are familiar with context then try it, for the beginner you move like action to App.js and pass it as a prop just like you did for setErrorMessage. Also, add empty useEffect with blogs dependency in App.js so its change will cause re-render.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement