Next.js Discord

Discord Forum

Passing functions between components

Unanswered
Kublick posted this in #help-forum
Open in Discord
Hello Im building a AddToCart functionality..
I have a server component, that retrieves the product via the slug..
On the page I have a cart like section that I converted to a client component..
What I want to do its to handle the amount with a useState.
interface Props {
  product: Product;
}

const AddToCart = ({ product }: Props) => {
  const [size, setSize] = useState<Size | undefined>();
  const [quantity, setQuantity] = useState<number>(1);

  return (
    <>
      <SizeSelector
        availableSizes={product.sizes}
        selectedSize={size}
        onSizeChanged={setSize}
      />

      <QuantitySelector quantity={quantity} onQuantityChanged={setQuantity} />

      <button type="button" className="btn-primary my-5">
        Add to Cart
      </button>
    </>
  );
};

export default AddToCart;

SizeSelector component
interface Props {
  selectedSize?: Size;
  availableSizes: Size[];
  onSizeChanged: (size: Size) => void;
}

const SizeSelector = ({
  selectedSize,
  availableSizes,
  onSizeChanged,
}: Props) => {
  return (
    <div className="my-5 ">
      <h3 className="mb-4 font-bold">Available Sizes</h3>
      <div className="flex">
        {availableSizes.map((size) => (
          <button
            onClick={() => {
              console.log(size);
              onSizeChanged(size);
            }}
            type="button"
            key={size}
            className={clsx("mx-2 hover:underline", {
              underline: size === selectedSize,
            })}
          >
            {size}
          </button>
        ))}
      </div>
    </div>
  );
};

export default SizeSelector;

When I click in the button I will see the console log of the value of size... but afterward I will get an error of onSizeChanged is not a function... but it comes from useState... Im doing something wrong ?

0 Replies