How to create a Like & Unlike rating feature using React and PHP

Creating a "Like" and "Unlike" rating feature using React and PHP involves several steps. In this example, we'll use a simple PHP backend to store and retrieve user ratings, and React for the frontend. We'll create a basic web application that allows users to like or unlike an item and displays the total number of likes. Here's a step-by-step guide:

Step 1: Set Up Your Environment

Make sure you have the following installed:

  • A web server with PHP support (e.g., Apache, Nginx).
  • Composer for PHP package management.
  • Node.js and npm for React development.
  • Create a new directory for your project.

Step 2: Create the PHP Backend

  • Inside your project directory, create a folder named api.
  • In the api folder, create a new file named index.php to handle API requests:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "GET") {
    // Simulate retrieving the like count from a database
    $likeCount = 5; // Replace with your logic to fetch the actual like count
    echo json_encode(["likes" => $likeCount]);
} elseif ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Simulate updating the like count in a database
    $likeCount = 6; // Replace with your logic to update the actual like count
    echo json_encode(["likes" => $likeCount]);
}
?>

This simple PHP script provides an API endpoint for getting and updating the like count. In a real application, you would interact with a database.

Step 3: Set Up Your React Application

  • In your project directory, open a terminal and run the following commands to create a React app:
npx create-react-app my-like-app
cd my-like-app
  • Install Axios for making HTTP requests:
npm install axios

Step 4: Create the React Component

  • Replace the contents of src/App.js with the following React component:
import React, { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [likes, setLikes] = useState(0);
  const [liked, setLiked] = useState(false);

  useEffect(() => {
    // Fetch the initial like count from the API
    axios.get("http://your-api-url/index.php").then((response) => {
      setLikes(response.data.likes);
    });
  }, []);

  const handleLike = () => {
    // Simulate sending a like request to the API
    axios.post("http://your-api-url/index.php").then((response) => {
      setLikes(response.data.likes);
      setLiked(true);
    });
  };

  const handleUnlike = () => {
    // Simulate sending an unlike request to the API
    axios.post("http://your-api-url/index.php").then((response) => {
      setLikes(response.data.likes);
      setLiked(false);
    });
  };

  return (
    <div className="App">
      <h1>Like & Unlike Example</h1>
      <p>Total Likes: {likes}</p>
      {!liked ? (
        <button onClick={handleLike}>Like</button>
      ) : (
        <button onClick={handleUnlike}>Unlike</button>
      )}
    </div>
  );
}

export default App;

Replace http://your-api-url/index.php with the actual URL of your PHP API.

Step 5: Start the React App

In the terminal, run the following command to start your React development server:

npm start

Your React app should now be running, and you can access it in your web browser.

This example provides a basic setup for a "Like" and "Unlike" feature using React and PHP. In a real application, you would replace the simulated API calls with actual database interactions and implement user authentication to prevent multiple likes from the same user.

Muhammad Alfaiz
Alfaiz 3 months ago
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x