Ben Aston Ben Aston - 2 years ago 76
Javascript Question

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

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?


feels horrible.

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

componentWillUnmount() {'myEvent', componentDidReceiveEvent)

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

render() {
return (<div>
{ => <MyNode key={} />)}

MyComponent.propTypes = {
id: React.PropTypes.string,
webSocket: React.PropTypes.oneOfType([

Answer Source

If the setTimeout feels hacky (a view I tend to agree with), you could use the transitionend event instead.

The transitionend event is fired when a CSS transition has completed. In the case where a transition is removed before completion, such as if the transition-property is removed or display is set to "none", then the event will not be generated.

Aside from that I don't really see anything wrong with your approach

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download