I have the following Cart.tsx code with two functions onRemove and onAdd with .bind() passing some data:
const Cart = (props: CartProps) => {
// ...
const cartItemRemoveHandler = (id: string) => {
console.log("CartItemRemoveHandler");
};
const cartItemAddHandler = (item: CartItemProps) => {
console.log("CartItemAddHandler");
};
const cartItems = (
<ul className={classes["cart-items"]}>
{cartCtx.items.map((item) => (
<CartItem
key={item.id}
id={item.id}
name={item.name}
amount={item.amount}
price={item.price}
onRemove={cartItemRemoveHandler.bind(null, item.id)}
onAdd={cartItemAddHandler.bind(null, item)}
/>
))}
</ul>
);
// ...
};
CartItem.tsx:
export interface CartItemProps {
id: string;
name: string;
amount: number;
price: number;
onAdd?: (id: string) => void;
onRemove?: (item: CartItemProps) => void;
}
const CartItem = (props: CartItemProps) => {
const price = `$${props.price.toFixed(2)}`;
return (
<li className={classes["cart-item"]}>
<div>
<h2>{props.name}</h2>
<div className={classes.summary}>
<span className={classes.price}>{price}</span>
<span className={classes.amount}>x {props.amount}</span>
</div>
</div>
<div className={classes.actions}>
<button onClick={props.onRemove}>-</button>
<button onClick={props.onAdd}>+</button>
</div>
</li>
);
};
The error occurs at CartItem.tsx at the onClick functions in the buttons. The onClick is red underlined with the following error:
(JSX attribute) React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined
Type '((id: string) => void) | undefined' is not assignable to type 'MouseEventHandler<HTMLButtonElement> | undefined'.
Type '((id: string) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.
Types of parameters 'id' and 'event' are incompatible.
Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is not assignable to type 'string'
The expected type comes from property 'onClick' which is declared here on type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'
I don't need the event properties. I just want the function to execute whenever the button is clicked. Can I work around this? Help is appreciated.
Update: Solved the error by changing the interface onAdd and onRemove declarations to: onAdd?: () => void; and onRemove?: () => void;. Essentially, I just removed the parameters from the functions in the interface, which results in the following:
export interface CartItemProps {
id: string;
name: string;
amount: number;
price: number;
onAdd?: () => void;
onRemove?: () => void;
}
The .bind() functions are handling the arguments. There is no need to define them in the interface as well, which was my mistake.
onClick={() => props.onRemove}