I have built a minimal ReactJS component to update the number of likes. All works well but the count does not update when clicked. I tried following several answers but cannot figure out why.
See the code:
import React, {useState} from 'react';
class GiveLikes extends React.Component {
// set the initial value of the likes
state = {likes:0};
// Function is called every time "likes" is clicked
likes_count = (likes) =>{
// Counter state is incremented
this.state({likes: likes+1});
}
render() {
return (
<>
<h2> {this.state.likes} </h2>
<div className="buttons">
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginRight: '5px',
backgroundColor: 'green',
borderRadius: '8%',
color: 'white',
}}
onClick={() => this.likes_count}>Likes
</button>
</div>
</>
)
}
}
export default GiveLikes;
The above code will render the following on the web browser. Clicking the "Likes" should update the value of the count, but unfortunately it does not.
likes_count()
methodthis.setState({likes: this.state.likes +1});
instead of this.state({likes: this.state.likes +1});
import React, {useState} from 'react';
class GiveLikes extends React.Component {
constructor(props) {
super(props);
this.state = {likes: 0};
}
likes_count = () => {
this.setState({likes: this.state.likes +1});
}
render() {
return (
<>
<h2> {this.state.likes} </h2>
<div className="buttons">
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginRight: '5px',
backgroundColor: 'green',
borderRadius: '8%',
color: 'white',
}}
onClick={this.likes_count}>Likes
</button>
</div>
</>
)
}
}
export default GiveLikes;