React Native - The Animated.spring function experiences a flickering issue when the animation is reverted

I am currently working on implementing a drawer in my react native app. The issue I am facing is with the closing animation. When I click the close button, the animation seems to blink or flicker, as if it is opening and closing multiple times before finally shutting.

Here is the code snippet where I define the drawer functionality:

export default class Drawer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            height: new Animated.Value(0)
        }
    }

    showContent = () => {
        Animated.spring(this.state.height, {toValue:130}).start();
    }

    hideContent = () => {
        Animated.spring(this.state.height, {toValue:0}).start();
    }

    render() {
        return (
            <View>
                <TouchableHighlight 
                    onPress={this.showContent}
                    underlayColor="transparent"
                >
                    <Text>Show</Text>
                </TouchableHighlight>

                <TouchableHighlight 
                    onPress={this.hideContent}
                    underlayColor="transparent"
                >
                    <Text>Hide</Text>
                </TouchableHighlight>

                <Animated.View style={{height: this.state.height}}>
                    <Text>Content</Text>
                </Animated.View>
            </View>
        );
    }
}

Answer №1

When the animation seems to flicker, it's due to the use of a spring animation that rebounds or bounces when it reaches its final value. To eliminate this bounce effect, try substituting spring with timing:

showContent = () => {
    Animated.timing(this.state.height, {toValue:130}).start();
}

hideContent = () => {
    Animated.timing(this.state.height, {toValue:0}).start();
} 

Answer №2

Encountered a similar problem recently. I found that using Animated.spring still works, but make sure to set the appropriate minimum height for some extra flexibility. It seems that this required minimum height can vary - in my situation, setting it to 2 allowed for a maximum height of 55.

Answer №3

Although I arrived a bit tardy, I managed to resolve the problem by simply utilizing the configuration bounciness: 0 to fully eliminate the blink.

For further details, you can explore the documentation provided.

Answer №4

While this question may be several years old, I encountered the same issue recently and found a solution that worked for me. It seems to be one of the top results on Google, so I'm sharing what fixed it in my case.

Here is the animation code snippet:

const progressBarAnimation = useRef(new Animated.Value(progressBarValue)).current;

useEffect(() => {
    Animated.spring(progressBarAnimation, {
      toValue: progressBarValue(),
      speed: 10,
      bounciness: 10,
      useNativeDriver: false,
    }).start();
  }, [progressBarValue]);

The problem was resolved by incorporating interpolation with the extrapolate: 'clamp' setting:

const animatedWidth = progressBarAnimation.interpolate({
    inputRange: [0, 100],
    outputRange: ['0%', '100%'],
    extrapolate: 'clamp',
  });

To implement it, you can simply do this:

<Animated.View style={{ width: animatedWidth }}/>

Without extrapolate: 'clamp', the progress bar would overshoot from 0 to 100% multiple times before settling back at 0%. This adjustment prevented that behavior.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way in jQuery to display a particular div with a unique id when a link is clicked?

I have a div with the following structure: <article id="#pippo">blablabla</article> which I have hidden using jQuery $('article').hide(); Now, I want to create a link menu that displays a specific article id when it's clicked ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

When using a callback function to update the state in React, the child component is not refreshing with the most recent properties

Lately, I've come across a peculiar issue involving the React state setter and component re-rendering. In my parent component, I have an object whose value I update using an input field. I then pass this updated state to a child component to display t ...

What is the best way to show the totals on a calculator screen?

As part of my work, I created a calculator to help potential clients determine their potential savings. Everything seems to be working fine, except for the total fees not appearing for all the boxes. I believe I might be missing the correct process to add ...

`amqplib - What is the current number of active consumers on the queue?`

Seeking insight on using the amqplib module for Node JS and RabbitMQ: 1) Is there a method to determine the number of subscribers on a queue? 2) What is the process for ensuring that each queue has only one consumer key? Appreciate any guidance! ...

Error Handling with Node.js Sequelize RangeError

Currently, I am in the process of setting up a table to store user sessions. Specifically, I plan to save the IP address as an integer and have been exploring various methods for achieving this. You can find more information on this topic here: IP-addresse ...

What is the best way to handle texture loading delays in Three.js when using a JSON model?

Currently, I have successfully loaded a JSON model based on AlteredQualia's skinning example. However, I am looking to hide the model until it is fully loaded. In the provided example, the models are displayed before their texture resources finish loa ...

What is the best method to access an element with Vue.js?

I currently have a form set up like this <form v-on:submit.prevent="save_data(this)"></form> and a method defined in Vue.js like this methods: { save_data: function(f){ } } In jQuery, we can access the form using $(f)[0] My question ...

Ways to effectively pass arguments to the callback function within the catch function in JavaScript

While working on my code, I suddenly felt the need to pass an extra argument, "msg", to the callback function renderError(). This extra argument should be passed along with the default error argument generated by the catch function itself. I tried doing i ...

The React error message refuses to disappear even after attempting to refresh the page

Currently, I am immersed in a React project where I have encountered an issue on the Register Page. All errors are being added to a Message component. Interestingly, even after encountering a React error (such as 'Cannot read properties of undefined&a ...

What is the most effective method for incorporating access token authentication in a React application?

As a newcomer to React, I am working on implementing authentication using Express.js in my react web application. I have successfully set the token in response cookies on the backend with the HttpOnly flag, but unfortunately, I am unable to read it on the ...

What is the most effective way to add images to a table using JavaScript?

Is there a way to insert images into the "choicesDiv" without having to make changes to the HTML & CSS? Here is the table code: <table id="choices"> <tr> <td><div class="choicesDiv" value="1"></div></td> ...

cheerio scraping results in an array that is devoid of any data

Struggling to extract data from a website with the URL https://buff.163.com/market/csgo#tab=buying&page_num=1 using request-promise and cheerio. Check out my code snippet below: const request = require('request-promise'); const cheerio = requ ...

verifying for incorrectly formatted object within a JSON list

I'm facing an issue where I need to convert a list of objects into an array. Everything works smoothly when the objects are in good shape, however, it becomes quite challenging to identify which one is malformed when dealing with 4000 records. Is ther ...

Retrieving information from the API to populate a child component in Next.js

I have been developing a header component and here's the code snippet: import style from '../../styles/header.css'; import '../../styles/globals.css'; export default function Header({data}){ const [showMe, setShowMe] = useStat ...

Having trouble pinpointing the issue with this particular if statement?

I am currently working on creating a form that compiles all entered data when the user fills out all fields. The form is connected to a PHP file and functions properly, but I encountered issues when implementing validation logic. The "Validation" section ...

The class (module) is not available for export

Module: import typeIs from './helpers/typeIs'; /** * @description Class of checking and throwing a custom exception. */ export default class Inspector { // Some code } In package.json specified the path to the file: { // .... "main" ...

An issue arises when attempting to utilize v-model with a file input

Is there a way to reset a file input field in Vue.js after uploading a file? I attempted to set the v-model value to null, but encountered an error message that said: File inputs are read only. Use a v-on:change listener instead. This is my current cod ...

The jQuery script version 3.5.1 encountered an error at line 4055 where DataTables was unable to access the property "aDataSort" due to it

Hey there, I'm currently facing a small challenge while trying to incorporate Datatables within a bootstrap modal to display the results of a SQL Server query. The main requirement is to provide the option to export the data as an Excel file or in oth ...

Close session when browser/tab is exited

After extensive searching online, I have been unable to find a satisfactory solution for ending a session when a browser or tab is closed without requiring the user to log off. I have attempted numerous JavaScript codes that I came across, but none of the ...