Home > Back-end >  Call Function out of React Component
Call Function out of React Component

Time:02-11

I want to update a shopping cart when I click on a Product. But I don't know, how to call the function in another component.

This is, where the function is written and the state of the cart is hold.

    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");
    
    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };
    
    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }
...
}

Here I want to call the addToCart function.

import { Cart } from "../../sites/Cart/Cart";
...

 <div className="product-name">
                    <button
                        className="button is-small is-outlined is-primary"
                        onClick={() =>
                            Cart.addToCart(product.id) & changeButtonText
                        }
                    >
                        {buttonText}
                    </button>
                </div>

When I try to execute this, I get the following error message: enter image description here

Do you have any suggestion for me?

Thank you very much!

CodePudding user response:

You can not do this like that. Below I wrote simple example and here is nice article I suggest to read it first: Components and Props

const AddToCartButton = ({ setCart }) => {
  return (
    <button
      onClick={() => {
        setCart("item");
      }}
    ></button>
  );
};
const Cart = () => {
  const [cart, setCart] = React.useState([]);
  return <AddToCartButton setCart={setCart} />;
};

CodePudding user response:

Methods in React return JSX values ​​and in this way it is not correct to export a method, if you want to export the method of addToCart to a another component you need to send this method as propeties or using state management for example as follows:

    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");
    
    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };
    
    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }

   return <AnotherComponent addCartFunc={addToCart} />

}

Then you can use this method in the host component as follows:

export const Cart = ({addCartFunc}) => {
   return (
        <div className="product-name">
            <button
                className="button is-small is-outlined is-primary"
                onClick={() =>
                    addCartFunc(product.id) & changeButtonText
                }
            >
                {buttonText}
            </button>
        </div>
   )
}
  • Related