1

I have an absolutely positioned div:

class MyDiv extends React.Component {
  state = {
    stepCount: 0
  };

  componentDidMount(){
    setInterval(() => {
      this.setState({ stepCount: this.state.stepCount + 1 })
    }, 1000);
  }

  render(){
    return (<div style={{ left: this.state.stepCount * 10 + "%" }} />);
  }
}

CSS
div { transition: 1s linear; }

Every second, I translate the div left by 10%. I want the transitions to look smooth, but there is a slight stutter.

Example: https://codepen.io/anon/pen/QoNGbQ

Don P
  • 60,113
  • 114
  • 300
  • 432
  • there are several animation libraries for react, If you plan to do different types of animations in several places, using a library is better than doing manul css-transitions. Try `react-spring` for example. – Raihanul Mar 02 '19 at 11:17

2 Answers2

0

Use css transforms instead of position for animations. It is more performant.

  render(){
    return (<div style={{ transform: `translateX(${this.state.step * 3 + "%"})`}} />);
  }

See this article on medium

Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
0

You're probably best off using CSS transforms or a module such as react-spring, but if neither of them suit you then you want requestAnimationFrame.

(CSS Transforms can make text blurry CSS transition effect makes image blurry / moves image 1px, in Chrome? and for a one-off you might not want the bundle load of an external module)

https://codesandbox.io/s/pj9m554nkj

const animate = ({ timing, draw, duration }) => {
  let start = performance.now();

  const animateLoop = time => {
    const durationFraction = Math.min(
      1,
      Math.max(0, (time - start) / duration)
    );
    const progress = timing(durationFraction);
    draw(progress);
    if (durationFraction < 1) {
      requestAnimationFrame(animateLoop);
    }
  };

  requestAnimationFrame(animateLoop);
};

const MovingDiv = ({ move, duration }) => {
  const [pos, setPos] = useState(0);
  useEffect(() => {
    animate({
      timing: fraction => move * fraction,
      draw: progress => setPos(progress),
      duration
    });
  }, []);

  return <div className="MovingDiv" style={{ left: pos }} />;
};

You can also then start playing with easeIn/easeOut in the timing function to add a bit of spring.. https://codesandbox.io/s/2w6ww8oymp

lecstor
  • 5,619
  • 21
  • 27