Skip to content
Advertisement

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>
        
  )
      }

Advertisement

Answer

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>
  );
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement