Shifting the size of a React element with animation

Within my React-based application, I am attempting to execute a basic CSS3 width transition with the following code:

.foo {
    transition: width 1s ease-in-out;
}

My objective is to apply a style to an element in the React component which is "width: xx%" and then animate it from 0% to xx%. However, due to the element having this property upon rendering, the animation fails to work. Even after exploring "ReactCSSTransitionGroup", I have not been able to find a solution. I have even tried using setTimeOut to set the style attribute after the component has been rendered, but this approach feels messy and like a hack. Can anyone provide guidance on the correct approach to achieving this?

Answer №1

If you want to animate a component once it has been rendered (from 0 to n%), you can achieve this by using setState within the componentDidMount lifecycle method. Since browsers do not re-render elements that have changed in the same animation frame but rather merge the changes and render the final result, it is necessary to wrap the setState call in a requestAnimationFrame.

For a detailed explanation, you can refer to this blog post.

The code implementation will be as follows:

export default class AnimateMe extends Component {
  state = {
    width: 0
  };

  componentDidMount() {
    requestAnimationFrame(() => {
      this.setState({ width: "75%" });
    });
  }

  render() {
    return (
      <div style={{ width: this.state.width }}>
        Animate my width
      </div>
    );
  }
}

For a live example, you can check out this working demo: https://codesandbox.io/s/7z1j794oy1

I hope this information proves to be useful!

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

Executing a search and replace function using a delay within a foreach loop - the ultimate guide

Below is a snippet of code where I attempt to perform find and replace within an array by searching for keys and replacing them with corresponding values. However, the expected functionality does not work as intended, leading to multiple searches for &apos ...

What is the correct way to establish an array variable containing objects?

What is the correct way to declare an object within an array variable? I encountered the following error message: "TypeError: Cannot set property 'name' of undefined" Here is the code snippet in question: let data = [] data[0].name = "john" ...

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...

Acquire information from a JSON formatted string

I am having trouble extracting the first name from the JSON data provided below. While I am able to display the entire string using JavaScript [ alert(data); ], I am struggling to isolate just the first names. Any assistance would be greatly appreciated! ...

MUI: encountering issue with setting background color on Paper component

I am having trouble styling the MUI <Paper> component. I have tried to change the background color using CSS, but it remains white despite other properties like padding and text-align working fine. Can someone please advise me on what I might be ov ...

Headerbar overlapping Div when scrolling

I'm currently trying to create a fixed header bar that allows the content of the page to scroll beneath it rather than displaying above it. This functionality is working on multiple pages, but I'm experiencing issues with my calendar page. When ...

What is the best way to make multiple HTML tables sortable?

I recently implemented an open-source JavaScript table sorter in my project. You can find more information about it here: However, I encountered an issue where only the most recently added table on my page is sortable. When users press a button, new table ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Tips for leveraging async and await within actions on google and API integration

Currently, I am developing an Actions on Google project that utilizes an API. To handle the API calls, I am using request promise for implementation. Upon testing the API call, I observed that it takes approximately 0.5 seconds to retrieve the data. Theref ...

AngularJS and CSS: A Guide to Effortlessly Toggle Sliding List Elements

I am in the process of developing a drop-down menu that can be clicked. Using my custom AngularJS directive, I have successfully implemented functionality to load menu items dynamically. While I have made significant progress, I have encountered a small i ...

Exploring the world of jQuery and Ajax: Experimenting with implementing a POST method through Ajax and retrieving the response in HTML

Hey guys, I'm currently attempting to set up a basic HTML post method using Ajax. Take a look at the code snippet below: <?PHP function fetchInstagramData($url) { $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => ...

The process of testing the catch part in jest and @testing-library/react

ComponentFile.js <Button onClick={ async e =>{ clearForm(); }} Reset </Button> const clearForm = () => { try{ someRef.current.clearFormData(); const display = document.getElementById("errorDisplayDi ...

Changing state on click in React Child and Parent Components---Note: The topic

I'm currently working on making a button in a child React component change the Boolean state of both the child and its parent when clicked. It's quite challenging to ensure that both components' states are updated simultaneously. To see the ...

What is the best way to uppercase each element in an array using only a while loop in plain ECMAScript 5?

Struggling with a simple exercise that requires converting names to uppercase and passing them to an empty array using only while loop(s) in plain JavaScript: var names = ['rob', 'dwayne', 'james', 'larry', 'st ...

Is your Firebase Google sign-in popup window flashing and not successfully signing in while using Vue.js?

After implementing the Google sign-in pop-up method in Vue.js, I encountered an issue where the live Google sign-in popup window kept flashing and never successfully signed in. However, this problem did not occur when testing locally. Below is the code fo ...

In JavaScript, using window["functionName"](arguments) will result in a TypeError message saying that the function does not exist

When trying to execute an AJAX function based on the active tab in my application, everything works smoothly when I trigger the function after specific events. However, I encounter difficulties when attempting to call the function using a dynamically gener ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

What is the connection between {{result}} and $scope.result within AngularJS?

I comprehend the concept of binding a model to an element. An example would be... <pre ng-model="result">. This connection is established through the $scope.result variable. However, how are these two related? {{result}} $scope.result = data; ...

Transforming all commas to plus signs in a JavaScript codebase for the entirety of

Currently, I am using winston for logging and have created a common method to log throughout the project. However, I am facing an issue with many logging statements that look like this: logger.info("here is the data" , data) The problem arises when trying ...