React Like button

import cx from 'classnames';
import { Component } from 'react';

export default class LikeButton extends Component {
    state = {
        count: 100,
        liked: false
    }
    likeMe = () => {
        let newCount;
        if(this.state.liked) {
            newCount = this.state.count - 1;
        } else {
            newCount = this.state.count + 1;
        }

        this.setState({
          count: newCount,
          liked: !this.state.liked
        })
    }
    
    render() {
        return (
            <div>
                <div>
                    <h1 
                    className={`like-button ${this.state.liked ? "liked" : ""}`}
                    onClick={this.likeMe}
                    >Like | <span className={`likes-counter`}>{this.state.count}</span></h1>
                </div>
                <style>{`
                    .like-button {
                        font-weight: normal;
                        cursor: pointer;
                        font-family: Helvetica, Arial, Sans-Serif;
                        font-size: 1rem;
                        padding: 5px 10px;
                        color: #585858;
                        border: 1px solid #585858;
                        display: inline-block;
                    }
                   .liked {
                        font-weight: bold;
                        color: #1565c0;
                        border-color: #1565c0;
                   }
                `}</style>
            </div>
        );
    }
}

Leave a Comment