Open In App

How to Create a Responsive Like Button in ReactJS?

React is a JavaScript library used to develop interactive user interfaces. We will be making a Like feature using React JS. 
Modules required:

npm install --save @fortawesome/react-fontawesome

Basic setup: Start a project by the following command:



npx create-react-app like-app
cd like-app
npm start
mkdir components && cd components && touch Like.js

The directory structure will look similar to this:



Edit Like.js as following. 

Like.js: Final Code of the component which can be exported and used inside any other component.




import React, { Component } from "react";
import { faHeart } from "@fortawesome/free-solid-svg-icons";
import { faHeartBroken } from "@fortawesome/free-solid-svg-icons";
  
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
class Like extends Component {
  state = { liked: false };
  toggle = () => {
    let localLiked = this.state.liked;
  
    // Toggle the state variable liked
    localLiked = !localLiked;
    this.setState({ liked: localLiked });
  };
  render() {
    return (
      <div className="container">
        <center>
          <p>Click on the Like Button</p>
          <div
            className="container"
            style={{ border: "1px solid black", width: "15%" }}
            onClick={() => this.toggle()}
          >
            {this.state.liked === false ? (
              <FontAwesomeIcon icon={faHeart} />
            ) : (
              <FontAwesomeIcon icon={faHeartBroken} />
            )}
          </div>
        </center>
      </div>
    );
  }
}
  
export default Like;

Output: Final Output will look something like this. Open http://localhost:3000/ in browser:


Article Tags :