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

What are some methods for simulating user interaction on input and button elements?

Here is a code snippet available in this stackblitz demo. Essentially, there is a basic form with an input field and a button. Clicking the button will copy the current value of the input to a label: https://i.stack.imgur.com/pw3en.png after click: htt ...

Learn how to create a pop-up modal that appears when a form is successfully submitted in React JS, automatically hides after 2 minutes, and redirects to another page

Hey there! I'm looking to create a pop-up modal in React JS that opens when a form is successfully submitted. The modal should automatically hide after 5 minutes and then redirect to another page. Can anyone guide me on how to implement this functiona ...

NodeJS JSONStream causing memory exhaustion issue

I've encountered an issue while trying to stream a large JSON file (94mb in size) from an HTTP request to a local file using the JSONStream library in NodeJS. Despite setting a memory flag of 256mb with node --max-old-space-size=256 .\main.js, th ...

What is the best way to cut and combine multiple array elements in the right positions?

let result = response.data; console.log(result); const newTemp = result.ssps_with_scated.splice(5,1).concat(result.ps_with_ed.splice(2,1))[0]; result.ps_with_ed.push(newTemp); After multiple attempts, I finally achieved my goal. However, the array values ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...

The output is: [object of type HTMLSpanElement]

<form> <table> <tr> <td>Distance:</td> <td><input type="number" id="distance" onKeyUp="calculate();">m</td> </tr> <tr> <td>Time:</td> ...

When working with Vue, setting the default value for props as a computed property is an

props: { rules: { type: Array, required: false, default: () => [ (file) => !file || file.size < 10000000 || this.getJsonDataByLocale.less_than_10mb_message, (file) ...

Node and Socket.IO - Personalized messaging (one-on-one)

I'm in the process of developing a one-on-one chat feature using Socket.IO and Express to enable private messaging between users. The main issue at hand is: I am looking for a way to send a private message to a specific socket.id while ensuring that ...

Transmit information using jQuery to an MVC controller

I am developing an ASP.NET MVC3 application and need to send three pieces of data to a specific action when the user clicks on an anchor tag: <a onclick='sendData(<#= Data1,Data2,Data3 #>)'></a> Here is the javascript function ...

Is it possible to align a CSS table row with its corresponding table header even when the table row is deeply nested within the table structure?

I am looking to keep the structure of my HTML code consistent and unaltered. However, this has resulted in a form tag being nested inside a table row before the table cells can begin. The information I need to display is tabulated data, which makes CSS t ...

I am having trouble comprehending this JavaScript code, could someone provide me with assistance?

Currently delving into the world of JavaScript functions and stumbled upon this code snippet with the following output: Output: "buy 3 bottles of milk" "Hello master, here is your 0 change" function getMilk(money, costPerBottle) { ...

Adjust the maximum and minimum values on a dual thumb slider

I have implemented a two thumb range slider to define the maximum and minimum values. However, I recently discovered that it is possible for the thumbs to cross over each other - the max value can exceed the min value and vice versa. I am looking for a s ...

Encountering a hiccup while trying to install dependencies, neither the --force nor --legacy-peer-deps flags have been

Embarking on a new project with React, I encountered an error while attempting to install the dependencies outlined in the tutorial video I am following. Unfortunately, I'm uncertain how to resolve this issue on my own. The list of dependencies and c ...

Get the Zip file content using PushStreamContent JavaScript

I am looking for the correct method to download a PushStreamContent within a Post request. I have already set up the backend request like this: private static HttpClient Client { get; } = new HttpClient(); public HttpResponseMessage Get() { var filenames ...

Challenges with displaying HTML website on mobile platform

Hey there! I admit that my website may not be the greatest, but bear in mind that this is just a school project page. My current issue is with the mobile view styling - the hamburger menu should replace the nav bar on smaller screens, but it's not wor ...

Preventing Angular button click when an invalid input is focused out

Here is a Plunker link http://plnkr.co/edit/XVCtNX29hFfXtvREYtVF?p=preview that I have prepared. In this example, I've asked you to: 1. Enter something in the input field. 2. Click directly on the button without interacting with any other element. ...

Utilize dynamic global variables in React that are provided during runtime, making them unpredictable during the build process

I am currently developing an application for Overwolf, which you can find more information about at For this platform, applications are built using html/js and run in the Overwolf Browser. The browser provides access to the Overwolf API through a global v ...

How to toggle hidden links with AngularJS or vanilla JavaScript with a click事件

When the "Show all" button is clicked, I would like to display all elements. If the "1st half" link is clicked, I want to show "abc", "def", and "ghi". When the 2nd link "2nd half" is clicked, I want to display "jkl", "mno", and "pqr". Then, when the "show ...

The magic of Angular's data binding post-ajax retrieval

My situation is as follows: /items/item/123/edit and I have a controller that combines both the view and edit functionalities: ... if ($routeParams.id) { $scope.itemId = $routeParams.id; $scope.editMode = true; Item.getB ...

Having trouble with redundant code while updating state in ReactJS - React JS

Currently, I am working on a prayer times web app using reactJS (nextjs). To achieve this, I first fetch the geolocation coordinates and then retrieve the city and country name based on these coordinates. Following that, I obtain the prayer times for the s ...