CSS transition not working when I set a className dynamically in React

Viewed 38

I've got an hamburger menu but I want to add another className to it when clicked so it could rotate but the issue here is the transition property not working when added to the parent element but it does seems to work when added individually to the span element inside the the hamburger.

this is the initial css style

.navbar__hamburger {
    position: relative;
    display: none;
    flex-direction: column;
    row-gap: 0.2rem;

    @include respond(desktop) {
      transition: all ease-in-out 5s;
      display: flex;
      z-index: 1000;
      cursor: pointer;
    }

    span {
      width: 2rem;
      height: 0.2rem;
      background-color: black;
    }

    span:nth-child(2) {
      width: 1rem;
      align-self: flex-end;
    }
  }

the css when the hamburger menu is clicked

.animation {
  span:nth-child(1) {
    transform: rotate(140deg);
  }

  span:nth-child(2) {
    opacity: 0;
  }

  span:nth-child(3) {
    position: absolute;
    transform: rotate(-140deg);
  }
} 

here's how the className was added when clicked

   const [isMenuOpen, setIsMenuOpen] = useState(false);

<div onClick={() => setIsMenuOpen(!isMenuOpen)} className={`navbar__hamburger ${isMenuOpen ? "animation" : ""}`}>
            <span></span>
            <span></span>
            <span></span>
         </div> 
1 Answers

Hello you should put transition: all 0.3s property on the element which you want to animate in your case i think

update your css

.navbar__hamburger span {transition: all 0.3s}
Related