Home > Back-end >  calling multiple function when onClick the Icon
calling multiple function when onClick the Icon

Time:06-18

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 />
 )
}

CodePudding user response:

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 />

CodePudding user response:

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 />
     )
    }
  • Related