"Clicking on one item at a time from the list will trigger a reaction in React

Hello, I'm fairly new to programming and currently tackling a challenging exercise that has me a bit stuck.

  1. Display 10 posts from the API in the browser - Working
  2. Show 3 related comments for each post - Working

The issue I'm facing is that when I click on a post from the feed, all other comments are being fetched and displayed below each respective post simultaneously. What I want to achieve is to only display the comment related to the clicked post and hide it when clicking on another post.

Additionally, I am looking to implement a "load more" button that appears every time a set of comments is displayed, allowing users to fetch the latest 10 comments when clicked.

Any advice or suggestions on maintaining clean and readable code would be greatly appreciated!

Thank you in advance;

:)

Check out the code snippet below:

import React from "react";
import axios from "axios";

const postsID = "/posts";
const commentsID = "/comments";
var postsURL = `https://jsonplaceholder.typicode.com${postsID}`;
var commentsURL = `https://jsonplaceholder.typicode.com${commentsID}`;

class Posts extends React.Component {
constructor(props) {
super(props);
this.state = {
  posts: [],
  comments: [],
  expanded: false,
  commentsToShow: 3
};
this.clicked = this.clicked.bind(this);
}

clicked() {
  axios.get(commentsURL).then(res => {
    console.log("comments:", res);
   this.setState({ comments: res.data });
 });
}

componentDidMount() {
 axios.get(postsURL).then(res => {
   console.log("posts:", res);
   this.setState({ posts: res.data });
 });
}

render() {

  return (
    <div className="container">
      <div className="jumbotron-div col s12">
        <ul className="collection">
          {this.state.posts.slice(0, 10).map(post => (
            <div>
              <div key={post.id} onClick={this.clicked}>
                <h5>User ID: {post.id}</h5>
                <p>Post: {post.body}</p>
              </div>
              <div>
                <ul className="collection">
                  {this.state.comments
                    .filter(comment => comment.postId === post.id)
                    .slice(0, 3)
                    .map(comment => (
                      <li key={comment.id}>
                        <p>Comment ID: {comment.postId}</p>
                        <p>Comment: {comment.body}</p>
                      </li>
                    ))}
                </ul>
              </div>
            </div>
          ))}
        </ul>
      </div>
     </div>
  );
}
}

export default Posts;

Answer №1

If a Post has the ability to either display or hide its comments, it is necessary for it to have its own state. This means that it should be implemented as its own component, for example:

 class Post extends React.Component {
   constructor(props) {
     super(props);
     this.state = { showComments: false };
   }

   render() {
     const { id, body, comments } = this.props;

     return (
         <div key={id} onClick={() => this.setState({showComments: true })}>
           <h5>User ID: {id}</h5>
           <p>Post: {body}</p>
        </div>
        <div>
          <ul className="collection">
            {this.state.showComments ? comments.slice(0, 3)
                .map(comment => (
                  <li key={comment.id}>
                    <p>Comment ID: {comment.postId}</p>
                    <p>Comment: {comment.body}</p>
                  </li>
                )) : ""}
            </ul>
          </div>
        </div>
      ))}
     );
   }
 }

To implement this, use <Post /> within the Posts component and pass all the necessary data to the Post component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The system reference 'Sys' is not defined in ASP.NET

I am trying to implement ajax functionality on the ASP.NET platform. To achieve this, I am using ScriptManager in conjunction with jQuery, and adding the script after the "document is ready" event. $(document).ready(function () { // sync {{scopeN ...

The Infinity value is accessible through the JavaScript Window Object

The other day, I decided to print out the global window object and was surprised to see that the first value was Infinity. I've searched for an explanation but haven't found a satisfactory answer. Can anyone shed some light on why this is include ...

Passing state to getStaticProps in Next JSLearn how to effectively pass state

I am currently fetching games from IGDB database using getStaticProps and it's all working perfectly. However, I now have a new requirement to implement game searching functionality using a text input field and a button. The challenge I'm facing ...

Prevent the selected option color in the select box from changing

My dropdown menu has been styled with an image, but when a user selects an option it turns blue. Unfortunately, the blue color shows on top of the image and looks unattractive. Is there a way to prevent this behavior using CSS? I want to maintain the selec ...

Is there a way to utilize jQuery for parsing the XML file?

When trying to parse the file, the value for "name" in the code is always an empty string. Here is my XML data: <row> <id>1</id> <AnrufenZahl>64</AnrufenZahl> <NameOperator>Ioan</NameOperator> </row> ...

Is there a way for one choice to influence the available answers and pricing of other selection options?

I need to create two selection boxes, one for print type and one for size. When a user selects "LUSTRE" in the first box, I want the second box to only display "17x25.5", "13x19", and "10x15" for that specific print type. The issue I'm facing is that ...

Angular Resolve Upon Application Reloading

Is there a way to postpone the initialization of my Application Controller (similar to using the 'resolve' attribute in the router) when reloading a page? Or more importantly, how can I delay the rendering of the view until my controller has succ ...

What is the best way to select the initial element from my class within my component using protractor?

Can anyone help me figure out how to click on the button in this component? I need guidance on navigating through the following path: Is xpath my only option for doing this? I believe a css locator could work as well, but I am unsure of how to construct ...

What is the best way to display errors from a Node backend on a React frontend?

When making an API call, I am encountering multiple errors. My goal is to display relevant errors from the backend on the frontend. For example, I would like to indicate the error 'Site name exist' on the frontend. Backend: if (Sname) { cons ...

Guide on clicking an element within a hidden iframe using Python Selenium

I am facing a challenge in finding elements within an iframe tag. Surprisingly, the HTML source does not contain any iframe tags. However, upon inspecting the element, I can see that there is indeed an iframe tag present. How can I tackle this issue using ...

What is the best approach for showcasing overflowing text in tables in a manner that is user-friendly?

I am seeking a solution for dynamically loading data in a table, where I want to wrap long text with ellipsis and display the full content elegantly on hover. Currently utilizing HTML and CSS for this purpose, I have encountered an issue. Even when the tex ...

Struggling to implement nested routes with react-router-dom version 5.2.0?

I'm currently working on implementing nested routing in React using react-router-dom 5.2.0. For a better understanding of the project, you can access the CodeSandbox link here: https://codesandbox.io/s/nested-routes-8c7wq?file=/src/App.js Let's ...

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

Creating a grid filled with random letters of the alphabet

Currently, I am in the process of working on a project that involves creating a 5x5 grid filled with random alphabetical characters (including the possibility of having multiple occurrences of the same letter). Although I have already developed a functio ...

Modify the React MUI GridToolbar's font style

Is there a way to adjust the font size of the GridToolbar? https://mui.com/x/react-data-grid/components/#toolbar <DataGrid {...data} components={{ Toolbar: GridToolbar, }} /> I attempted to change the font size using the following code: & ...

Unexpected behavior from vuelidate triggered on blur

I have implemented vuelidate for form validation. My goal is to validate user input either when they move to the next input field or click outside of the current one. <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$ ...

Utilizing Vue component data within inline CSS of a Vuetify component: a step-by-step guide

I am currently working on a list component that is dynamically generated from data and I have a specific requirement to style each item based on the color provided in the data. Here is an example of the Vue component: new Vue({ el: '#app', ...

What is the best way to ensure that a date is not earlier than the current date using jQuery?

I'm currently implementing a jQuery date picker in a textbox and I want to restrict the user from selecting a date earlier than the current date. Since I am new to jQuery and JavaScript, I would greatly appreciate some assistance with this issue. ...

I am interested in categorizing by month and calculating the total amount from the project's embedded document

Here is the image for my mongo-DB database collection: [1]: https://i.sstatic.net/TIKh1.png I am working on adding a query to get the sum of amounts grouped by month from an embedded array in the UserModel collection. Currently, I am implementing it as s ...

Unlocking the Power of Strapi v4: Leveraging Context within a Service

By creating a custom controller in Strapi, convenient access to a Context object is granted. This allows for retrieving the current user and utilizing the user's data as needed: module.exports = createCoreController("api::event.event", ({ st ...