Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I associate seperate state to each button?

Hello

I am trying to associate a like button with each PaperCard component as shown in the code below. I have included the relevant code. Currently, The like button shows up and every time you click it the counter increases BUT all the buttons share the same state. So I am trying to fix that. I am new to JS and React.

Any help will be appreciated. Thanks!

function Home() {
  
  const [likes, setLikes] = useState(0);

  const incrementLikes = () => {
    const addToLikes = likes + 1;
    setLikes(addToLikes)
    }
  const loadMorePapers = () => {
    setVisible((prevValue) => prevValue + 3);}

  return (
    <div>
      <div style={{display:'flex', justifyContent:'center'}}>
      <h1>Latest Papers</h1>
      </div>
      {apiData.slice(0, visible).map((paper) => (
        <Grid key={paper.title}>
          <button onClick={incrementLikes}>Likes: {likes}</button>
          <PaperCard title={paper.title} abstract={paper.abstract}/>
        </Grid>
      ))}
      <div style={{display:'flex', justifyContent: 'center'}}>
      <Button variant="contained" onClick={loadMorePapers}>Load More</Button>
      </div>
      </div>
        
  )
      }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The element from the map callback is extracted as a component, and now every button has its own state.

function Home() {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "center" }}>
        <h1>Latest Papers</h1>
      </div>
      {apiData.slice(0, visible).map((paper) => (
        <LikeButton paper={paper} key={paper.title} />
      ))}
      <div style={{ display: "flex", justifyContent: "center" }}>
        <button variant="contained" onClick={loadMorePapers}>Load More</button>
      </div>
    </div>
  );
}

function LikeButton(paper) {
  const [likes, setLikes] = useState(0);

  const incrementLikes = () => {
    const addToLikes = likes + 1;
    setLikes(addToLikes);
  };

  return (
    <div key={paper.title}>
      <button onClick={incrementLikes}>Likes: {likes}</button>
      <PaperCard title={paper.title} abstract={paper.abstract}/>
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading