React Request animation frame

React Request animation frame

by jonahe

HTML

<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<div id="root"></div>

CSS

.box {
  position: relative;
  top: 0;
  left: 0;
  display: inline-block;
  width: 40px;
  height: 40px;
  background-color: teal;
  border: solid 1px black;
}

.teal {
  background-color: teal;
}
.yellow {
  background-color: yellow;
}
.magenta {
  background-color: magenta;
}

Babel + JSX

class App extends React.Component {
	constructor(props) {
  	super(props);
    this.state = { left: 0 };
  }
  
  componentDidMount() {
  	this.animateSideway();
  }
  
  animateSideway() {
  	const {left} = this.state;
    let newLeft;
    if(left < 0 || left < 150) {
    	newLeft = left + 1;
    } else {
    	newLeft = 0;
    }
    requestAnimationFrame(() => {
    	this.setState({ left: newLeft }, this.animateSideway);
    });
  }
  
  render() {
  	const {left} = this.state;
		const style = { left, top: left };
    return (
    <div>
      <img height="70" src="https://media.giphy.com/media/3oEdva9BUHPIs2SkGk/giphy.gif"></img>
      <div className="box teal" style={ style }>
        <div className="box yellow" style={ style }>
          <div className="box magenta" style={ style } />
        </div>
      </div>
    </div>
    );
  }
}

ReactDOM.render(
	<App />, document.getElementById('root'));