Search code examples
javascriptreactjsweb-componentreact-propsreact-state

Reactjs : Update value of a component on click


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.

Rendered Image of the ReactJS component.


Solution

    1. Declare a constructor and initialize your state,
    2. Use an arrow function on your likes_count() method
    3. Use this.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;