Home > Back-end >  I want to pass a function to the active state and a different function to inactive state in react
I want to pass a function to the active state and a different function to inactive state in react

Time:01-21

function Product(props) {
const [Shop, setShop] = useState(false);
const Shopped = () => setShop(!Shop);
return(
<section onClick={() => { Shopped();}} >
    {!Shop ? (
         <FaShoppingCart
          title="افزودن به سبد خرید"
           className="absolute right-0 m-4 cursor-pointer hover:text-green-700"
            />) : 
           (<FaShoppingCart className="absolute right-0 m-4 cursor-pointer text-green-700" />
     )}
</section>
)}

export default Product

I want to pass addToCart() function to shop when its inactive. and pass removeFromCart() function when its active in react.

CodePudding user response:

You can create this prop with a condition:

<FaShoppingCart
  ...
  onClick={Shop ? removeFromCart : addToCart}
/>

CodePudding user response:

You can provide one function and change the functionality based on your Shop state.

function Product(props) {
  const [Shop, setShop] = useState(false);
  const Shopped = () => setShop(!Shop);

  const handleIconClick = () => {
    if (Shop === true) {
      removeFromCart();
    } else {
      addToCart();
    }
  };

  return (
    <section
      onClick={() => {
        Shopped();
      }}
    >
      {!Shop ? (
        <FaShoppingCart
          title="افزودن به سبد خرید"
          className="absolute right-0 m-4 cursor-pointer hover:text-green-700"
          onClick={handleIconClick}
        />
      ) : (
        <FaShoppingCart
          className="absolute right-0 m-4 cursor-pointer text-green-700"
          onClick={handleIconClick}
        />
      )}
    </section>
  );
}
  • Related