In React js, I wanted to display the animation specifically on the "add to bag" button for the added item

When I click the "add to bag" button, all other buttons also display the animation. How can I make sure that only the clicked button shows the animation? Any suggestions?

<Table responsive>
          <thead>
            <tr>
              <th>
                <p
                  className="p-2"
                  style={{ backgroundColor: "#F5F0E5", fontSize: "20px" }}
                >
                  SM
                </p>
              </th>
              {attributelist.map((attribute) => (
                <th key={variation.Name}>
                  <p
                    className="ml=5 p-2"
                    style={{ backgroundColor: "#F5F0E5", fontSize: "20px" }}
                  >
                    {attribute.Name}
                  </p>
                </th>
              ))}
              <th>
                <p
                  className="ml=5 p-2"
                  style={{ backgroundColor: "#F5F0E5", fontSize: "20px" }}
                >
                  Price
                </p>
              </th>
              <th className="text-center" />
            </tr>
          </thead>
          {variation.map((variations) => (
            <tbody key={variations.ID}>
              <tr>
                <td className="text-dark">{variations.VariationSKU}</td>
                {variations.Attributes.map((attribute) => (
                  <td key={attribute.ID} className="text-dark">
                    {attribute.Value}
                  </td>
                ))}
                <td className="text-dark">
                  {`RM${variations.Price.toFixed(2)`}
                </td>
                <td>
                  <Button
                    id="Sproduct-btn"
                    className={`btn add-to-cart w-100 ${
                      addedId === variations.ID ? submitResponse.class : ""}`}
                    data-toggle="tooltip"
                    type="button"
                    tag={!user ? Link : "a"}
                    to={!user ? "/login" : ""}
                    disabled={
                      submitResponse.openState ||
                      Status === "Inactive"`

This is my button code within the table above

 const [submitResponse, setSubmitResponse] = useState({
    class: "",
    openState: false,
  });
  const [response, setResponse] = useState();
  const [addedId, setAddedId] = useState();

  const onSubmit = () => {
    response
      .then(() => {
        // if success add to cart, process success animation
        setSubmitResponse({
          class: "added",
          openState: true,
        });
        setTimeout(() => {
          setSubmitResponse({
            class: "added txtState",
            openState: true,
          });
        }, 10);
        setTimeout(() => {
          setSubmitResponse({
            class: "added",
            openState: true,
          });
        }, 3000);
        // reset back to normal after 3.5s
        setTimeout(() => {
          setSubmitResponse({
            class: "",
            openState: false,
          });
        }, 3500);
      })

      .catch(() => {
        // if failed add to cart, process danger animation
        setSubmitResponse({
          class: "danger",
          openState: true,
        });
        setTimeout(() => {
          setSubmitResponse({
            class: "danger txtState",
            openState: true,
          });
        }, 10);
        setTimeout(() => {
          setSubmitResponse({
            class: "danger",
            openState: true,
          });
        }, 3000);

        // reset back to normal after 3.5s
        setTimeout(() => {
          setSubmitResponse({
            class: "",
            openState: false,
          });
        }, 3500);
      });
  };

This is my onSubmit function for displaying the animation after adding an item

Answer №1

To apply the animation class to all buttons on the map:

className={`btn add-to-cart w-100 ${submitResponse.class}`}

You should use a conditional statement to determine which button was clicked. For instance, you could set up a state and assign the added variations.ID to it.

className={'btn add-to-cart w-100 '+((addedId===variations.ID)?(submitResponse.class):'')}

Latest Update :

I have a new suggestion for you:

You might need to make some adjustments:

I've modified your table component:

<Table responsive>
          <thead>
            <tr>
              <th>
                <p
                  className="p-2"
                  style={{ backgroundColor: "#F5F0E5", fontSize: "20px" }}
                >
                  SM
                </p>
              </th>
              {attributelist.map((attribute) => (
                <th key={variation.Name}>
                  <p
                    className="ml=5 p-2"
                    style={{ backgroundColor: "#F5F0E5", fontSize: "20px" }}
                  >
                    {attribute.Name}
                  </p>
                </th>
              ))}
              <th>
                <p
                  className="ml=5 p-2"
                  style={{ backgroundColor: "#F5F0E5", fontSize: "20px" }}
                >
                  Price
                </p>
              </th>
              <th className="text-center" />
            </tr>
          </thead>
          <tbody>
          {variation.map((variations) => (
              <TableRow variation={variations} />
          ))}
          </tbody>
          
        </Table>

Remember to pass the variation to each TableRow Component:

function TableRow({variation}) {


  const [submitResponse, setSubmitResponse] = useState({
    class: "",
    openState: false,
  });
  const [response, setResponse] = useState();

  const onSubmit = () => {
    response
      .then(() => {
        // if success add to cart, process success animation
        setSubmitResponse({
          class: "added",
          openState: true,
        });
        setTimeout(() => {
          setSubmitResponse({
            class: "added txtState",
            openState: true,
          });
        }, 10);
        setTimeout(() => {
          setSubmitResponse({
            class: "added",
            openState: true,
          });
        }, 3000);
        // reset back to normal after 3.5s
        setTimeout(() => {
          setSubmitResponse({
            class: "",
            openState: false,
          });
        }, 3500);
      })

      .catch(() => {
        // if failed add to cart, process danger animation
        setSubmitResponse({
          class: "danger",
          openState: true,
        });
        setTimeout(() => {
          setSubmitResponse({
            class: "danger txtState",
            openState: true,
          });
        }, 10);
        setTimeout(() => {
          setSubmitResponse({
            class: "danger",
            openState: true,
          });
        }, 3000);

        // reset back to normal after 3.5s
        setTimeout(() => {
          setSubmitResponse({
            class: "",
            openState: false,
          });
        }, 3500);
      });
  };


  return (<tr key={variations.ID}>
    <td className="text-dark">{variations.VariationSKU}</td>
    {variations.Attributes.map((attribute) => (
      <td key={attribute.ID} className="text-dark">
        {attribute.Value}
      </td>
    ))}
    <td className="text-dark">
      {`RM${variations.Price.toFixed(2)`}}
    </td>
    <td>
      <Button
        id="Sproduct-btn"
        className={`btn add-to-cart w-100 ${ submitResponse.class }`}
        data-toggle="tooltip"
        type="button"
        tag={!user ? Link : "a"}
        to={!user ? "/login" : ""}
        disabled={
          submitResponse.openState ||
          Status === "Inactive" ||
          variationStatus === "Inactive" ||
          Stock === 0 ||
          variationStock === 0
        }
        style={{ fontSize: "15px", width: "30%" }}
        {...(user && {
          onClick: () =>
            onSubmit(
              setResponse(addToCart(productid, variations.ID))
            ),
        })}
      >
        <div className="cart">
          <div>
            <div />
            <div />
          </div>
        </div>
        <div className="dots" />
        {/* {variationStock === 0 || data.data.Stock === 0 ? (
    <div className="pl-2 default">SOLD OUT</div>
  ) : (
    <span className="pl-2 default">ADD TO BAG</span>
  )} */}
        <span className="pl-2 default">{result}</span>
        <div className="success">ADDED</div>
        <div className="failed">
          FAILED TO ADDED, PLEASE TRY AGAIN
        </div>
      </Button>
    </td>
  </tr>)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for displaying res.locals information in the console for debugging purposes using ExpressJS and Nodejs

Currently, I am delving into the world of Node.js and ExpressJS as a novice in this realm. My primary requirement is to log the entire or partial content of res.locals in my console for debugging purposes. Here's what I've attempted: var foo_ro ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

Balancing lifecycle methods with makeStyles for component styling in Material UI

Whenever I attempt to utilize makeStyles() with a component that has lifecycle methods, I encounter the following error: Invalid hook call. Hooks are only allowed to be called within the body of a functional component. This issue could arise due to the ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

How can you prevent the browser from prompting to save your email and password when filling out a sign-up form?

I'm currently developing a PHP sign up form, but whenever I click on the sign up button, the browser prompts me to save the email and password. Is there a way to prevent this from happening? ...

Retrieving object by a value within a nested array in Javascript

I need to retrieve all objects that have a specific 'id' within a nested array. Specifically, I want to find all person objects with hobbies id of 2 (hiking) in the provided sample data. This inquiry tackles the challenge of extracting all value ...

Picture failed to load

I am struggling to get an image to display on my webpage, as only the alt text is appearing. Here is the code I am using: return ( <> <div className="container my-5"> <div className="row ju ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

TypeError: "Table" has not been declared

This is my first experience with the script editor. I have been given the task of creating a pivot table for Google Sheets using a script. // This script creates a pivot table in Google Sheets function createPivotTable() { var ss = SpreadsheetApp.getAc ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

Error: Authorization required to access server-side resource [POST http://localhost:3000/serverSide] - Status

I'm having an issue with sending a username and password from an HTML file to a Javascript file that queries an employee table for authentication. The problem arises when the username and password are set to undefined in my serverSide.js file, prevent ...

The error message "getStaticPaths is not a valid method in NextUI/NextJS"

Encountering a Type Error: getStaticPaths is not a function specifically when using NextUI components like Buttons or Chips is becoming a roadblock for me. This issue has resurfaced, and the previous solution that worked before does not seem to be effecti ...

What is the best way to extract values from a JavaScript function?

As someone who is new to Javascript, I am interested in learning how to retrieve values from a function. In the given code snippet, my goal is to extract TheName, TheHeight, TheGender, and TheSexuality when executing the function so that I can utilize the ...

Navigate to the specified location using AJAX

When I update a comment using AJAX, I want to automatically scroll down to the updated comment: $("#aggiorna").click(function(){ var value = $("#id").val(); var dato = $("#comment_edit").val(); var dato1 = $("#user_id").val(); var dato2 = ...

Ways to modify the color of mat-icon within an input field using Angular 6

Here is the code from my HTML file: <div class="input-field"> <div> <input type="text" id="name" required email/> <label for="name">Email: <mat-icon svgIcon="mail" class="change-color"></mat-icon> &l ...

Encountering a 401 error without any accompanying message when attempting to generate a teams meeting link through the Azure Graph client in Node.js

Just starting out with Azure and here is my code snippet: I have set the necessary permissions. Check them here const { startDateTimeAsync, endDateTimeAsync } = require('./dateTimeFormat'); const { ClientSecretCredential } = require('@azure ...

Animating objects in ThreeJS to traverse multiple positions smoothly with linear interpolation (lerp)

I am exploring ways to animate a sphere's movement along a predefined sequence of vertices. I have successfully managed to animate the sphere from one point to another using the code below: function animate() { requestAnimationFrame(animate) spher ...

"Responsive header design using Bootstrap for both desktop and mobile devices

Is there a way to create a header that adjusts its width based on the device viewing it, with maximum width for desktop and no padding for mobile? Here is an example of the code: <div class="row"> <div class="span12"> ...

Reactify TypeScript: Accurate typings for onChange event

How can I resolve the issues with types for target: { value: any, name: any }? The errors I encounter include Duplicate identifier 'any'. and Binding element 'any' implicitly has an 'any' type.. Additionally, why does the erro ...