tiedantebreak
tiedantebreak

Reputation: 89

How to change the icon of a button when it is clicked, button already has a on click event

I want to change the icon on the button whenever it is clicked, The button has onClick event to add product to basket.

      <Button
          style={{ backgroundColor: "transparent" }}
          type="primary"
          icon={<img src={plusCart} />}
          onClick={addToBasket}
        />

Upvotes: 0

Views: 922

Answers (3)

Yaman KATBY
Yaman KATBY

Reputation: 2023

const [buttonClicked, setButtonClicked] = useState(false);

const addToBasket = () => {
  ...
  setButtonClicked(true);
};

...

<Button
  ...
  icon={<img src={buttonClicked ? someIcon : plusCart} />}
  onClick={addToBasket}
/>

Upvotes: 2

Wraithy
Wraithy

Reputation: 2056

You can store information if button was clicked in useState hook and onClick change this state:

const [clicked, setClicked] = React.useState(false)

return(
 <Button
          style={{ backgroundColor: "transparent" }}
          type="primary"
          icon={<img src={clicked ? plusCart : minusCart} />}
          onClick={(e)=>{
           setClicked(true);
           addToBasket(e);}}
        />
)

Upvotes: 1

Jasmin Heifa
Jasmin Heifa

Reputation: 46

You can use a boolean state for this, maybe like so:

const [buttonClicked, setButtonClicked] = useState(false);

const addToBasket = () => {
  setButtonClicked(true);
  // your code..

};

<Button
          style={{ backgroundColor: "transparent" }}
          type="primary"
          icon={buttonClicked ? <img src={otherIcon}/> : <img src={plusCart}/>}
          onClick={addToBasket}
        />

Upvotes: 1

Related Questions