0

I have an animation that I want to use in a react.js component.

@keyframes pulse {
    0% {
        background-color: #94A3B8;
    }

    50% {
        background-color: #CBD5E1;
    }

    100% {
        background-color: #94A3B8;
    }
}

I can put it in a CSS file and import it into the react component. then i can reference it like this:

<div style={{animation: "pulse"}}></div>

I'm curious if animation can be defined in the component. something like this:

const animation = `
@keyframes pulse {
    0% {
        background-color: #94A3B8;
    }

    50% {
        background-color: #CBD5E1;
    }

    100% {
        background-color: #94A3B8;
    }
}
`

<div style={{ keyframes: animation }}></div>
Arman Zanjani
  • 197
  • 11

1 Answers1

1

The easiest way is to use the <style> tagg to insert inline styling:

class ExampleClass extends React.Component {
  render() {
    return (
      <div>
        <h2>{'Test Inline Animation'}</h2>
        <div className='animate'>{'WhoeeeHoeee'}</div>
        <style>
            {`
                .animate {
                    animation-name: pulse;
                    animation-duration: 4s;
                }
                @keyframes pulse {
                    0% {
                        background-color: #94A3B8;
                    }

                    50% {
                        background-color: #CBD5E1;
                    }

                    100% {
                        background-color: #94A3B8;
                    }
                }
            `}
        </style>
      </div>
    );
  }
}

ReactDOM.render(<ExampleClass />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • thanks. I think that is the answer. but I have to sure the style tag is inside the head tag. maybe this can help other people: https://gist.github.com/yamadayuki/f1ea9ccacad7f1c140457b5877fb54cc – Arman Zanjani Mar 14 '21 at 17:05