Open In App

How to create Like Button Using React JS ?

Last Updated : 15 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

This is a social media world and the like button is one of the main components of it. From social media accounts to shopping platforms like buttons are everywhere.

In this tutorial, we'll explore how to create a dynamic button in a React application. The button will change its appearance based on different states, including default, hover, and liked. Additionally, we'll incorporate asynchronous handling for API calls when the button is clicked.

Preview of final output: Let us have a look at how the final output will look like.

dsfghjfg

Prerequisites

Approach to create Like button:

The task is to design a like button with the following states:

  • Default State: The button appears in a default state.
  • Hover State: When hovered, the button turns red.
  • Liked State: After clicking, the button transitions to a loading state, indicating that an API call is in progress. The API can either succeed or fail, affecting the final state of the button.

Steps to Create the Project

Step 1: Set Up Your React App with Vite

npm create vite@latest

ddd

Step 2: Navigate to the Project Directory

cd like-button

Step 3: Install the project dependencies using:

npm install

Project Structure:

Screenshot-2024-02-10-130538
project structure

The updated dependencies in package.json will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.55",
"@types/react-dom": "^18.2.19",
"@vitejs/plugin-react-swc": "^3.5.0",
"eslint": "^8.56.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"vite": "^5.1.0"
}

Example: Create the required files and add the following code.

JavaScript
// App.jsx

import { HeartIcon, SpinnerIcon } from "./Icon";
import { useState } from "react";
import "./App.css";

export default function App() {
    const [liked, setLiked] = useState(false);
    const [isFetching, setIsFetching] = useState(false);
    const [error, setError] = useState(null);

    const handleLikeUnlike = async () => {
        setError(null);
        setIsFetching(true);

        try {
            const response = await fetch(
                "https://www.greatfrontend.com/api/questions/like-button",
                {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({
                        action: liked ? "unlike" : "like",
                    }),
                }
            );

            if (response.status >= 200 && response.status < 300) {
                setLiked(!liked);
            } else {
                const res = await response.json();
                setError(res.message);
                return;
            }
        } finally {
            setIsFetching(false);
        }
    };

    return (
        <div>
            <button
                onClick={handleLikeUnlike}
                className={`likeBtn ${liked ? "liked" : ""}`}
            >
                {isFetching ? <SpinnerIcon /> : <HeartIcon />}
                {liked ? "Liked" : "Like"}
            </button>
            {error && <div className="error">{error}</div>}
        </div>
    );
}
JavaScript JavaScript CSS

Steps to run the application:

Step 1: Type the following command in the terminal.

npm run dev

Step 2: Open web browser and type the following URL.

http://localhost:5173/

Output:

Recording2024-02-10130925-ezgifcom-video-to-gif-converter
output

Next Article

Similar Reads

three90RightbarBannerImg