'Create a simple like button component with React

SOLUTION JAVASCRIPT:

How create to Build a “like button” component using React 16. The component should be the default export (use export default).

Click here image



Solution 1:[1]

Personally, I prefer to use functional components instead of using class-based components. One solution to your problem could be the following code.

import React, { useState } from 'react';


const LikeButton = () => {
  const [likes, setLikes] = useState(100);
  const [isClicked, setIsClicked] = useState(false);

  const handleClick = () => {
    if (isClicked) {
      setLikes(likes - 1);
    } else {
      setLikes(likes + 1);
    }
    setIsClicked(!isClicked);
  };

  return (
    <button className={ `like-button ${isClicked && 'liked'}` } onClick={ handleClick }>
      <span className="likes-counter">{ `Like | ${likes}` }</span>
    </button>
  );
};

export default LikeButton;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael Abusleme