Search code examples
javascriptreactjsbuttoncounterstyled-components

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

  • 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;