I am making a simple website in React that has two like buttons. Each like button is in different Card components and both of these are in a parent Projects component. I want the total number of likes on the website not to exceed and 10. so button one registered 4 likes the second one cannot register more than 6 likes. This is my initial code and it just gives the same state for both Card components
import styles from "./Card.module.css";
const Card = ({ img, title, description, ytLink, children}) => {
return (
<div className={styles.card}>
<img className={styles["card-media"]} alt={img.alt} {...img} />
<div className={styles["card-details"]}>
<h2 className={styles["card-head"]}>{title}</h2>
<p>{description}</p>
<div className={styles.buttons}>
<a
key={ytLink}
className={styles["card-action-button"]}
href={ytLink}
target="_blank"
>
Watch
</a>
{children}
</div>
</div>
</div>
);
};
export default Card;
import Card from "../Card";
import styles from "./Projects.module.css";
import React, { useState, useEffect } from "react";
import Likebutton from "../Like";
const Projects = ({ projects }) => {
const [likesCount, setLikesCount] = useState(0);
const addLike =() => {
const updateLikes = likesCount + 1;
updateLikes < 10 ? setLikesCount(updateLikes) : setLikesCount("10+");
}
const like=<Likebutton addLike={addLike} likesCount={likesCount}></Likebutton>
return (
<div className={styles.container}>
{projects.map((project) => (
<Card
key={project.title}
{...project}
>{like}</Card>
))}
</div>
);
};
export default Projects;
const Likes = () => {
const [likesA, setLikesA] = useState(0);
const [likesB, setLikesB] = useState(0);
const [message, setMessage] = useState();
const addLike =(like) => {
if(likesA + likesB < 10){
if(like == "A")
{
setLikesA(likesA +1)
}
if(like == "B")
{
setLikesB(likesB +1)
}
}
else{
setMessage("Limit was exceeded")
}
}
return (
<>
<div onClick = {() => addLike("A")}>
Add Like A
</div>
<div onClick = {() => addLike("B")}>
Add Like B
</div>
{message && message}
</>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.