Am trying to call two different function when the user onClick the Icon but am getting Error: Expected onClick listener to be a function, instead got a value of object type. please can someone to know what am doing wrong here.
Here's my code
function fullComponent (){
const dispatch = useDispatch();
const addItemToBasket = () => {
dispatch(
addToBasket({
id,
name,
price,
})
);
};
const TodoComponent = {
backgroundColor: "#44014C",
}
return (
<div> <StarBorderIcon onClick={addItemToBasket &&TodoComponent}<div />
)
}
Firsts and foremost, TodoComponent is not a function which makes your onClick a bit non-sensical.
One thing you can do if you want to invoke multiple functions with one onClick call is to create a onClickHandler function which bundles your function calls together, roughly speaking.
const function1 = () => {
...do something
}
const function2 = () => {
...do something else
}
const onClickHandler = () => {
function1()
function2()
}
<div><StarBorderIcon onClick={onClickHandler}<div />
You can use multiple functions by passing an anonymous function in onClick event as shown below
function fullComponent (){
const dispatch = useDispatch();
const addItemToBasket = () => {
dispatch(
addToBasket({
id,
name,
price,
})
);
};
const TodoComponent = {
backgroundColor: "#44014C",
}
return (
<div> <StarBorderIcon onClick={() => {
addItemToBasket();
TodoComponent();
}}
<div />
)
}
What you need to understand is that value1 && value2 will end up being either value1 or value2.
It will not hold both two values.
So if you come back to your original issue with addItemToBasket && TodoComponent, it will be just TodoComponent.
So complier is failing because TodoComponent is not an event handler.
If we imagine TodoComponent is a function, we can fix it like the following.
const onClickHandler = () => {
addItemToBasket();
TodoComponent()
}
<div><StarBorderIcon onClick={onClickHandler}<div />