CSS keyframe animation is not working on a react component

Viewed 128

I want to animate the menu icon on my website to rotate 45 degrees (with some +-) when I click on it. The current setup I have (following this tutorial) is as follows:

Navmobile.jsx:

const Navmobile = () => {
  const [open, setOpen] = useState(false);
  return (
    <div>
      {
        <img
          className="open-button h-[3vh] w-auto"
          src={openIcon}
          onClick={() => setOpen(true)}
          open={open}
        />
      }
      {open && <Dropdown />}
    </div>
  );
};

Navmobile.css:

.open-button[open="false"] {
  animation: rotate 500ms forwards; /* Animation titled rotate runs for 1s, once. */
}

@keyframes rotate {
  10% {
    transform: rotate(-5deg);
  }

  90% {
    transform: rotate(50deg);
  }

  100% {
    transform: rotate(45deg);
  }
}

However, when I click on the button, nothing happens. I can get it to work through the css hover property, but not through React. I also tested it on different browsers, so doesn't seem to be a browser issue either.

Does anyone know what I might be missing?

2 Answers

Try to add to className for your image onClick, not open atribute

<img
    className={`open-button h-[3vh] w-auto ${open ? 'open' : ''}`}
    src={openIcon}
    onClick={() => setOpen(true)}
/>

.open-button.open {
    animation: rotate 500ms forwards;
}

You have a problem with the false value, because open property is custom and has no value. You just leave open in the square brackets.

.open-button[open] {
  animation: rotate 500ms forwards; /* Animation titled rotate runs for 1s, once. */
}

Edit dazziling-code

Related