How to design a ReactJS component that listens to a WebSocket and interacts with CSS animation

Viewed 200

A ReactJS component needs to listen for events emitted by a WebSocket.

For each inbound event the component should render a DOM node.

It should then wait for the CSS animation associated with the DOM node to complete, and then remove the DOM node.

This is a sketch of my intended implementation.

Does this approach look workable?

The setTimeout feels horrible.

class MyComponent extends React.PureComponent {
 componentDidMount() {
    this.props.webSocket.on('myEvent', componentDidReceiveEvent)
  }

  componentWillUnmount() {
    this.props.webSocket.off('myEvent', componentDidReceiveEvent)  
  }

  // is this method style valid syntax?
  componentDidReceiveEvent = limit((evt) => {
    this.state.setState((prev, props) => {
      return {
        ...prev,
        inboundEvents: [...prev.events, evt]
      };
      setTimeout(function() {
        // use Array API to remove evt from the 
        // inboundEvents array on this.state
      }, DURATION_OF_CSS_ANIMATION);
    });
  })

  render() {
    return (<div>
      {this.state.events.map(e => <MyNode key={evt.id} />)}
    </div>);
  }
}

MyComponent.propTypes = {
  id: React.PropTypes.string,
  webSocket: React.PropTypes.oneOfType([
    React.PropTypes.bool,
    React.PropTypes.object,
  ]),
};
2 Answers
Related