Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Use keyframes property with React using inline style
const injectStyle = (style) => {
const styleElement = document.createElement('style');
let styleSheet = null;
styleSheet = styleElement.sheet;
styleSheet.insertRule(style, styleSheet.cssRules.length);
export default injectStyle;
import React from 'react';
import injectStyle from './path/to/injectStyle';
export default class SampleComponent extends React.Component {
constructor(props) {
const keyframesStyle = `
@-webkit-keyframes pulse {
0% { background-color: #fecd6d; }
25% { background-color: #ef7b88; }
50% { background-color: #acdacf; }
75% { background-color: #87c3db; }
100% { background-color: #fecd6d; }
injectStyle(keyframesStyle); = {
container: {
WebkitAnimation: 'pulse 10s linear infinite',
title: {
fontSize: '2rem',
render() {
const { style } = this.state;
return (
<div style={style.container}>
<h3 style={style.title}>Hello world using React!</h3>
Copy link

leoskyrocker commented May 25, 2017

This has a fundamental difference from using inline styles, i.e. inline styles doesn't pollute the global styles. With the injection here, it injects to the global scope which I would say defeats the purpose of inline styles.


Copy link

captncraig commented Jul 1, 2017

I like this a lot. @leoi11 is right, this does pollute the global styles, but I think this solves a different problem: for when you want styles distributed in the same file as the component itself. You could potentially make it pretty safe by prefixing selectors with the component name, but you would need to be very careful to make that perfectly safe.


Copy link

tleite commented Feb 10, 2020

This is the stuff that makes me hate React


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment