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>
2

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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: gist.github.com/yamadayuki/f1ea9ccacad7f1c140457b5877fb54cc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.