Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

onclick button toggle icon not working in reactjs

Here i try to toggle react icons when click the button but it still not working:

Here is my code:

const [anchorEl, setAnchorEl] = useState(null);

  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

   <button onClick={handleClick} className="top-rated-car-react-button">
            {anchorEl ? (
              <MdFavoriteBorder
                style={{
                  color: "#F76631", 
                }}
              />
            ) : (
              <MdFavorite
                style={{
                  color: "#F76631",
                }}
              />
            )}
   </button>

I try with react icons buttons onClick event but it is not toggling with both icons if MdFavoriteBorder it should change with MdFavorite when click the button same as when MdFavorite active change with MdFavoriteBorder

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Looks too complicated. I would create a boolean state which I would toggle then like this:

import { useState } from "react";
import { MdFavorite, MdFavoriteBorder } from "react-icons/md";

export default function App() {
  const [favorite, setFavorite] = useState(false);
  const toggleFavorite = () => setFavorite((prev) => !prev);

  return (
    <button onClick={toggleFavorite} className="top-rated-car-react-button">
      {favorite ? (
        <MdFavoriteBorder style={{ color: "#F76631" }} />
      ) : (
        <MdFavorite style={{ color: "#F76631" }} />
      )}
    </button>
  );
}

https://codesandbox.io/s/cool-poincare-wm1ite

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading