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!
JavaScript
x
30
30
1
function Home() {
2
3
const [likes, setLikes] = useState(0);
4
5
const incrementLikes = () => {
6
const addToLikes = likes + 1;
7
setLikes(addToLikes)
8
}
9
const loadMorePapers = () => {
10
setVisible((prevValue) => prevValue + 3);}
11
12
return (
13
<div>
14
<div style={{display:'flex', justifyContent:'center'}}>
15
<h1>Latest Papers</h1>
16
</div>
17
{apiData.slice(0, visible).map((paper) => (
18
<Grid key={paper.title}>
19
<button onClick={incrementLikes}>Likes: {likes}</button>
20
<PaperCard title={paper.title} abstract={paper.abstract}/>
21
</Grid>
22
))}
23
<div style={{display:'flex', justifyContent: 'center'}}>
24
<Button variant="contained" onClick={loadMorePapers}>Load More</Button>
25
</div>
26
</div>
27
28
)
29
}
30
Advertisement
Answer
The element from the map callback is extracted as a component, and now every button has its own state.
JavaScript
1
32
32
1
function Home() {
2
return (
3
<div>
4
<div style={{ display: "flex", justifyContent: "center" }}>
5
<h1>Latest Papers</h1>
6
</div>
7
{apiData.slice(0, visible).map((paper) => (
8
<LikeButton paper={paper} key={paper.title} />
9
))}
10
<div style={{ display: "flex", justifyContent: "center" }}>
11
<button variant="contained" onClick={loadMorePapers}>Load More</button>
12
</div>
13
</div>
14
);
15
}
16
17
function LikeButton(paper) {
18
const [likes, setLikes] = useState(0);
19
20
const incrementLikes = () => {
21
const addToLikes = likes + 1;
22
setLikes(addToLikes);
23
};
24
25
return (
26
<div key={paper.title}>
27
<button onClick={incrementLikes}>Likes: {likes}</button>
28
<PaperCard title={paper.title} abstract={paper.abstract}/>
29
</div>
30
);
31
}
32