Animation not happening In React Component

47 Views Asked by At

I am trying to achieve animation in a react app. The styles are getting imported from .js file (CSS in JS?). And those styles are getting applied except for the animation. The animation isn't working.

Styles.js containing styles is as below:

import { keyframes } from '@emotion/react';

const bounceAnimation = keyframes`
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(20px);
  }
`;
const classes = {
  loadingContainer: {
    fontSize: '84px',
    fontWeight: 800,
    textAlign: 'center',
  },
  loadingSpan: {
    display: 'inline-block',
    animation: `${bounceAnimation} 0.7s infinite`,
    color: 'red',
    margin: '0 -.05em',
  },
};

export default classes;

The React Component is as below:

import React from 'react';
import styles from './styles';

const Loader = () => {
  return (
    <div style={styles.loadingContainer}>
      <span style={styles.loadingSpan}>loading</span>
    </div>
  );
};

export default Loader;

1

There are 1 best solutions below

3
Dat Huynh On BEST ANSWER

You should use css API from '@emotion/react' like this:

/** @jsxImportSource @emotion/react */
import { css, keyframes } from '@emotion/react'

const bounce = keyframes`
  from, 20%, 53%, 80%, to {
    transform: translate3d(0,0,0);
  }

  40%, 43% {
    transform: translate3d(0, -30px, 0);
  }

  70% {
    transform: translate3d(0, -15px, 0);
  }

  90% {
    transform: translate3d(0,-4px,0);
  }
`

render(
  <div
    css={css`
      animation: ${bounce} 1s ease infinite;
    `}
  >
    some bouncing text!
  </div>
)

UPDATE: add /** @jsxImportSource @emotion/react */ is required.