Ad

React Animate Element When Property Changes?

- 1 answer

How to fade in an element when a property changes ?

I'd like the element returned by the statusMessage() function to fade in each time the this.props.statusMessage changes.

Currently no animations are applied. It doesn't appear as though any classnames are added either.

class SelectPlayer extends React.Component {

  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    selectedId = this.props.selectedId;
    selectedPlayerName = this.props.selectedPlayerName;
    Store.dispatch(Actions.updateScore(selectedId, selectedPlayerName));
  }

  statusMessage() {
    return (
      <ReactCSSTransitionGroup
        transitionName='message'
        transitionAppear={true}
        transitionAppearTimeout={2000}
        transitionEnterTimeout={500}
        transitionLeaveTimeout={500}>
          <div key="1">{this.props.statusMessage.text}</div>
      </ReactCSSTransitionGroup>
    )
  }

  render() {
    if (this.props.selectedPlayerName) {
      return (
        <div className="details">
          <div className="name">{this.props.selectedPlayerName}</div>
          <button className="inc" onClick={this.handleClick}>
            Add 5 points
          </button>
          { this.statusMessage() }
        </div>
      );
    }
    else {
      return (
        <div className="message">Click a player to select</div>
      );
    }
  }
};

CSS

.message {
  line-height: 2.25rem;
  text-align: center;
}

.message-appear {
  opacity: 0.01;
}

.message-appear.message-appear-active{
  opacity: 1;
}
Ad

Answer

I had a similar issue a few weeks ago. The issue is that the ReactCSSTransitionGroup needs to be rendered before it's children. In your example both ReactCSSTransitionGroup and this.props.statusMessage.text will be rendered at the same time when this.props.selectedPlayerName === true.

I found this article that might be useful: here

Recently while using the ReactCSSTransitionGroup add-on for React.js, I ran into the issue of not being able to apply the enter transitions to the child elements when the component is first rendered to the DOM.

When the component is initially rendered, both the ReactCSSTransitionGroup and all of its child elements appear in the DOM at the same time. However, the ReactCSSTransitionGroup will only apply the appropriate animation classes to any child elements which enter the DOM after the initial render.

Ad
source: stackoverflow.com
Ad