简体   繁体   中英

React element width animation

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM