Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use requestAnimationFrame in React Native

Tags:

react-native

How to use requestAnimationFrame in react native.

I use this for the performance of TouchableOpacity like this

this.requestAnimationFrame(() => {
    if (this.state.scrollEnabled)
        this._panel.transitionTo({toValue: 0});
    else {
        this.setState({scrollEnabled: true}, () => {
            this._panel.transitionTo({toValue: height})
        })
    }
});

And return this error

this.requestAnimationFrame is not a function

like image 384
Mahdi Bashirpour Avatar asked Jul 10 '18 06:07

Mahdi Bashirpour


People also ask

How do I use requestAnimationFrame in react native?

The requestAnimationFrame method returns an integer ID which can be used to cancel the queued request using the cancelAnimationFrame(id) method. The animation callback function can also accept a timestamp value, which is the time elapsed in milliseconds since the web page was loaded.

What is requestAnimationFrame react native?

requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.

Is requestAnimationFrame better than setInterval?

requestAnimationFrame() is much more efficient than setTimeout() or setInterval() , and the result is smoother and more accurate (just check the provided demo and the consumed CPU).

Where is requestAnimationFrame used?

The requestAnimationFrame() method tells the browser to run a callback function right before the next repaint happens. It's particularly useful when using JavaScript for animations and repeating UI updates.


2 Answers

You have to remove this from the first line:

requestAnimationFrame(() => {
      ....
});
like image 146
Behzad kahvand Avatar answered Nov 01 '22 01:11

Behzad kahvand


Update Nov 19: The previous documentation mentioned the TimerMixin I am referring to in my answer, but it's now been removed from the documentation. So using the native browser API should be the recommended approach (which is already the accepted answer).

Actually it is recommended not to use timing functions such as requestAnimationFrame directly in react-native. It's recommended to use TimerMixin instead, and doing that you end up calling it like the code in the original question.

So maybe a better answer would be "you're missing the TimerMixin".

Here's the official documentation explaining this bit: https://facebook.github.io/react-native/docs/timers#timermixin

like image 40
Noel De Martin Avatar answered Oct 31 '22 23:10

Noel De Martin