Skip to content Skip to sidebar Skip to footer

React Toggle Like Button

I have a component with a state: {likes: 123} I display the number of likes next to a 'like' button. How do I implement a functionality to this button, so when I click it once, it

Solution 1:

You could do something like the following.

Here is a codesandbox with a more complete version of the code.

importReactfrom'react';

classLikesextendsReact.Component {

  constructor(props){

    super(props);
    this.state = {
      likes: 124,
      updated: false
    };

  }

  updateLikes = () => {

    if(!this.state.updated) {
      this.setState((prevState, props) => {
        return {
          likes: prevState.likes + 1,
          updated: true
        };
      });

    } else {

      this.setState((prevState, props) => {
        return {
          likes: prevState.likes - 1,
          updated: false
        };
      });

    }
  }

  render(){

    return(
      <div><ponClick={this.updateLikes}>Like</p><p>{this.state.likes}</p></div>
    );
  }
}

exportdefaultLikes;

Post a Comment for "React Toggle Like Button"