Search code examples
reactjsemotion

Animations not working with Emotion Library


Relevant code:

const fadeInRight = keyframes`
    from {
        opacity:0;
        transform: translatex(-200px);
    }
    to {
        opacity:1;
        transform: translatex(0);
    }
`;
const bubbleFadeRight = css`
  animation: ${fadeInRight} 2s infinite;
`;

//check condition and set bubbleFade = bubbleFadeLeft or bubbleFadeRight
const bubbleFade = { bubbleFadeRight };

function App() {
  return (
    <div>
      {/* Not working: */}
      <div css={bubbleFade}>I blink!</div>

      {/* Working: */}
      <div
        css={css`
        // animation: ${bubbleFade}
      `}
      >
        I blink!
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Reproduction: https://codesandbox.io/s/dawn-rain-46ocm

Problem description: I don't know why when I use case 2, it's working but case 1 is not woriking.


Solution

  • The problem is that you are not assigning the animation CSS attribute properly, you don't need to re-define your css attribute:

        ...
        <div
         css={css`
         // animation: ${bubbleFade}
         `}
        >
        ...
    

    just assign it directly since you have bubbleFadeLeft and bubbleFadeRight as CSS variables

    like this:

      ...
      <div css={bubbleFadeLeft}>Case 1: I blink but not working!</div>
      <div css={bubbleFadeRight}>Case 2: I blink!</div>
      ...
    

    Here is a working codesandbox