Green
Green

Reputation: 5000

Reactjs animate a leaving component without using addon

In react.js, I am aware that animation can be performed using the addon ReactCSSTransitionGroup. As parts of a learning process, I am trying to write 'vanilla js' to animate a component on entering and on leaving.

I have come up with some simple codes as below, when the child component is mounted on entering

class Child extends React.Component {
  constructor(props) {
    super(props)
    this.state = { opacity: 0 }
  }
  componentDidMount() {
    this.setState({ opacity: 1 }) // change the opacity when the component is mounted
  }
  render() {
    <div style={{ transition: 'opacity 0.3s', opacity: this.state.opacity }}>
      I am a child component
    </div>
  }
}

class Parent extends React.Component {
  render() {
    return this.props.someProp === true ? <Child /> : null
  }
}

However, I am struggling on how to animate the component on leaving. componentWillUnmount does not work with this.setState({ opacity: 0 }), because the component will be removed. I have tried reading the source code in ReactCSSTransitionGroup but do not seem to get the gist. Can anyone provide a simple example code explaining how component on leaving should be implemented?

Upvotes: 1

Views: 93

Answers (1)

B.Gen.Jack.O.Neill
B.Gen.Jack.O.Neill

Reputation: 8397

The thing is, you can´t really handle this from within the component itself. That´s why you can only use React transitions on children of the ReactCSSTransitionGroup component. This is handled using new lifecycle methods added by ReactTransitionGroup element, as stated in docs.

Important method there is componentWillLeave(callback) which will not remove element from DOM untill callback is called. So if you want to implement similiar behavior yourself, you would need to take similar approach and create some wrapping component which could handle its children lifecycle and possibly extend it.

Upvotes: 1

Related Questions