Home > Software design >  Create a simple like button component with React
Create a simple like button component with React

Time:05-08

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

CodePudding user response:

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