so i created a counter for likes. i have 3 elements in total and i want when the user clicks on one of them that exact one is increment but so far if one is clicked on all are incremented pls help me out
class home extends Component {
constructor(props) {
super(props);
this.state = {
likeCounter: 0,
};
}
counter = () => {
this.setState((prevState) => ({
likeCounter: prevState.likeCounter + 1,
}));
};
render() {
return (
<>
<button className="click" onClick={this.counter}>
{this.state.likeCounter} likes
</button>
<button className="click" onClick={this.counter}>
{this.state.likeCounter} likes
</button>
<button className="click" onClick={this.counter}>
{this.state.likeCounter} likes
</button>
</>
);
}
}
I'd try it like this:
import React, {Component} from "react";
class Home extends Component {
constructor(props) {
super(props);
this.state = {};
}
counter = (counter) => {
this.setState((prevState) => ({
[counter]: prevState[counter] ? prevState[counter] + 1 : 1,
}));
};
render() {
return (
<>
<button onClick={() => this.counter(1)}>
{this.state[1] ? this.state[1] : 0} likes
</button>
<button onClick={() => this.counter(2)}>
{this.state[2] ? this.state[2] : 0} likes
</button>
<button onClick={() => this.counter(3)}>
{this.state[3] ? this.state[3] : 0} likes
</button>
<button onClick={() => this.counter(4)}>
{this.state[4] ? this.state[4] : 0} likes
</button>
</>
);
}
}
export default Home;
After you changed your question about "How to make these three buttons work" to "I got lot's of buttons, how would I do that" I would recommend you to create a single component that does the likes and include it several times (written as a functional component):
import React, { useState } from "react";
function LikeBtn() {
const [likes, setLikes] = useState(0);
return <button onClick={() => setLikes(likes + 1)}>{likes} likes</button>;
}
export default LikeBtn;
then use it in your app like this:
import React from "react";
import LikeBtn from "./LikeBtn";
export default function App() {
return (
<div>
<LikeBtn />
<LikeBtn />
<LikeBtn />
<LikeBtn />
<LikeBtn />
</div>
);
}