Home > Software engineering >  How to increment a value using onClick in react
How to increment a value using onClick in react

Time:10-17

I have a button when pressed onClick triggers LikeComment which posts the like to a DataBase using the current comment id and user who posted the comment.

    <button className="btn" onClick={LikeComment(comment_id, user_id)}>
      <div className="text">
        <i className="fas fa-thumbs-up"></i>
        <p>{comment_likes.length}</p>
      </div>
    </button>

What would be the best way to increment comment_likes.length when ever the button is pressed. Right now my problem is that the value only updates when page refreshes.

I have tried to do this, but It doesn't work as intended

<p>{comment_likes.length && LikeComment ? (comment_likes.length 1) : (comment_likes.length)}</p>

I want to achieve this by detecting when LikeComment is pressed to increment the original value by 1.

Any tips to tackle this would be appreciated..

CodePudding user response:

First of all you need to store the current like amount in the local state of the component. This way you can just display the current amount of likes and react will automatically update the display if you change the buttonLikes amount.

const [buttonLikes, setButtonLikes] = useState(comment_likes)

Then you'll need an event handler which will increment the like amount and post your changes to the DB


    const handleClickLikeButton = (comment_id, user_id) => {
        setButtonLikes((prevValue) => prevValue   1)
        LikeComment(comment_id, user_id)
    }

Now your display logic will look like this

   <button className="btn" onClick={handleButtonLike(comment_id, user_id)}>
      <div className="text">
        <i className="fas fa-thumbs-up"></i>
        <p>{buttonLikes}</p>
      </div>
    </button>
  • Related