The issue arises when trying to use Animate.timing in conjunction with the nativeEvent

I want to create a smooth animation where a View box slides down to its actual height. If the maximum height of the View, which is the height required to display all the contents, is less than 70, there is no need for an animation. However, if the maximum height exceeds 70, then I set the description height to 70. When the view is clicked, it should animate towards the maximum height. This is my objective.

Unfortunately, I am facing difficulties with the onLayout function in obtaining the necessary content height. Below is my code:

function card() {

    const [expandedDescription, setexpandedDescription] = useState(false);
    const [descriptionHeight, setdescriptionHeight] = useState(new Animated.Value(0))
    const [layoutCount, setlayoutCount] = useState(0)
    const [maxContentHeight, setmaxContentHeight] = useState(0);

    const getContentHeight = (event:any) => {
        setmaxContentHeight(event.nativeEvent.layout.height);
        if(maxContentHeight < 70){
            setdescriptionHeight(new Animated.Value(maxContentHeight));
        }
        else{
            setdescriptionHeight(new Animated.Value(70));
        }
    }

    const toggle = () => {
        console.log(maxContentHeight);
        if(maxContentHeight > 70){
            Animated.timing(descriptionHeight, {
                toValue: expandedDescription ? descriptionHeight : maxContentHeight,
                duration: 300,
            }).start();
            setexpandedDescription(!expandedDescription);
        }
    }

    return (
        <View style={styles.cardContainer}>
            <Animated.View style={[styles.descriptionContainer, {height:descriptionHeight}]} onLayout={(event:any) => getContentHeight(event)} >
                <Text style={styles.descriptionHeaderText}>Description</Text>
                <TouchableOpacity onPress={() => toggle()}>
                    <Text style={styles.descriptionText}>Lorem ipsum dolor sit amet, consectetur 
                        adipiscing elit. Aenean bibendum tincidfffffffffunt libero, nec luctus dolor consequat 
                        quis. Phasellus portalike elephants and had to work hard to earn their while chicken 
                    </Text>
                </TouchableOpacity>
            </Animated.View>
        </View>
    )
}

const styles = StyleSheet.create({
    cardContainer: {
        width: '95%',
        marginBottom: 10,
        backgroundColor: '#ffffff',
        borderRadius:25,
        height: 'auto',
        alignItems:'center',
        paddingLeft: 10,
        paddingRight: 10,
    },
    descriptionContainer:{
        width: '100%',
        alignItems:'center',
        marginTop: 10,
        padding:5
    },
    descriptionHeaderText:{
        fontSize: 15,
        color:'#8E8E8E',
    },
    descriptionText:{
        marginTop: 5,
    },
  });

export default card;

When I try to run the onLayout function to get the text box height dynamically, the animation starts behaving strangely. It either jumps between 0 and the maximum height or just stays at 0. Any suggestions or assistance would be greatly appreciated!

Answer №1

When working with useState, it is important to note that it is asynchronous. To improve performance and make the code more efficient, consider making these adjustments:

const getContentHeight = (event:any) => {
    const height = event.nativeEvent.layout.height;
    setmaxContentHeight(height);
    if(height < 70){
        setdescriptionHeight(new Animated.Value(height));
    }
    else{
        setdescriptionHeight(new Animated.Value(70));
    }
}

Additionally, keep in mind that the onLayout of animated components may operate differently. You can modify it like this:

       <Animated.View
          onLayout={Animated.event([
            {
              nativeEvent: {
                layout: {
                  height: maxContentHeight
                }
              }
            }
          ])}
        />

Then, you can set the description using useEffect(() => {...}, [maxContentHeight]) for better control and management.

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

Navigating in React Native with React Navigation or utilizing the power of React Hooks

When it comes to navigating between screens with React Native, how do the methods differ when using React Navigation compared to using hooks and functions for navigation? And is React Navigation the superior choice? ...

What methods can be used to verify the accuracy of an Oracle query?

Greetings Tech Enthusiasts, Currently, I am working on a .net application using C# that will provide users with a front end to write queries and view the results in a gridview table. I am facing a challenge in validating an Oracle query/syn ...

Opera browser encountering issue with styled image overlay in select list

We have implemented images in CSS to customize our select fields and they appear correctly in most browsers, except for Opera where the images are not displaying. To better illustrate the issue, I have set up a JSfiddle. Please try it out in Opera to expe ...

The background image is failing to display, although other styles for the class or element are visible

Why won't the background image display, even though I have verified that the image path is correct and changing other properties like color or background color works just fine? Here is my CSS code snippet: .container { background-imag ...

When a user clicks on a React listItem, the information for that specific item is displayed using

As a beginner in the coding world, I am currently learning about React and JSON. My project involves working on three interconnected panels. Specifically, I aim to showcase checklist answers on the third panel. First Panel: Displaying: All the ESN ("46 ...

How can I locate the next sibling element in JavaScript or jQuery?

I am currently working on a shopping cart feature with a view of the cart list count displayed. However, I have come across this particular code snippet in my document: <div class="input-group input-number-group"> <div class="in ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

Encountering a parsing issue: an unexpected token was found, expecting "," instead

I'm encountering a Parsing error that states: Unexpected token, expected ",". I've been unable to pinpoint where the missing "," is located. Please refer to the image below for the exact line of the error. const cartSlice = createSlice({ name ...

Having trouble converting JSON into a JavaScript object

I am encountering an issue with my HTML box: <span>Select department</span><span> <select id="department" onchange="EnableSlaveSelectBox(this)" data-slaveelaments='{"a": 1, "b": "2& ...

Is it possible to target only those divs within a class that wrap to a new line?

I currently have a series of 7 to 12 divs with the same styling, all floated to the left. Is there a CSS selector that can target the ones flowing onto a second row? I doubt this is achievable with standard CSS, so I'm curious if anyone has any jQuery ...

Obtain the HTML content when a user clicks on an image within a

I have implemented a plugin that allows me to scroll and zoom in on an image. My goal is to click on the following image to extract the values for left and top as specified below. <img id="zoom_mw" src="<?php echo $small_image; ?>" data-zoom-ima ...

I am encountering a 302 error when attempting to sideload images on Imgur using the API

I've been experimenting with sideloading using imgur's API. $.get("http://api.imgur.com/2/upload.json?", { url: www.example.com/blah.jpg },function(response){ var url = response.upload.links.original; var thumb_url = response ...

What is the best way to insert an HTML data attribute string into a SCSS mixin using attr()?

I'm currently working on setting up a color scheme in SCSS that allows me to use the following HTML structure: <div class="swatch" data-bg="green">...</div> In my SCSS file, I have defined a mixin like this: @function color($key: ' ...

How to verify that the user is using the most up-to-date version of the application in React Native

Currently, I am focused on the application and have implemented API endpoints that return the latest version along with information on whether the update is mandatory. Within the application flow, a GET request is sent to these API endpoints to check the ...

After an AJAX request, the URL is automatically updated with $_GET parameters

I have the following code snippet: $('#loginnow').click(function() { var login_useroremail = $('input[name="login_useroremail"]').val(); var login_password = $('input[name="login_password"]').val(); $.ajax ...

After modifying the select option, the input field remains disabled

I successfully developed a self-contained code snippet that toggles the enable/disable state of input fields. It works flawlessly on my HTML page. Check it out below: Identification Type: <select name="Identification-Type" id="Identification-Type"& ...

New replacement for the .selector method that has been eliminated in JQuery version 3.0

The JQuery version 3.0 has permanently removed the .selector property, leaving me confused about what to use as a replacement for it. I currently have utilized the .selector like this in my code: var TaxYearNode = $(EmployerLatestYear).find("TaxYear&q ...

Achieving opacity solely on the background within a div class can be accomplished by utilizing CSS properties such

Whenever I adjust the opacity of my main-body div class, it results in all elements within also becoming transparent. Ideally, I would like only the gray background to have opacity. See below for the code snippet: <div class="main1"> content </di ...

I'm sorry, but we are unable to process your request because the Webhook payload needs to be provided in either

Can anyone assist me with this issue? I'm facing a problem where I sent a request to https://my-server/api/webhook and received the following error: Webhook Error: Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffe ...

Requesting AJAX page yields a null $_GET parameter

Content loaded dynamically via AJAX methods. The base page is index.php, and profile.php is the page that gets loaded. The jQuery code snippet below has nothing to do with an HTML request: $('<a/>', {href: '?userID='+post[' ...