Reputation: 531
In my React based application I'm trying to perform a simple css3 width transition like:
.foo {
transition: width 1s ease-in-out;
}
what I want to do is set a style inside an element in the react component which is "width: xx%" and the animate it from 0% to xx%. Since the element when rendered already has this property the animation is not working. I've looked into the "ReactCSSTransitionGroup" but did not come closer to a solution. I started messing around with setTimeOut to set the style attribute after the component was rendered but it felt really messy and "hackish". Could someone point me in the right direction?
Upvotes: 4
Views: 5528
Reputation: 1371
If you are trying to animate the component after it has been rendered (from 0 to n%) you can do it by calling setState
in componentDidMount
. As browsers are not rerendering stuff that has changed in the same animation frame but merge changes and render the end result, you'll need to wrap it in requestAnimationFrame
I explained it throughly in this blog post.
Code will look like this:
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>
);
}
}
I made a working example: https://codesandbox.io/s/7z1j794oy1
Hope that helps!
Upvotes: 6