Search code examples
javascriptreactjsreactjs-flux

Flux/React design pattern


I'm writing a small Flux/React app that will display images in a gallery. I have a timer in a Flux store that pulls new images from a web service every 30 seconds and adds them to a list in the store, and then emits a change down so views can render the new photo.

I have all of that working but now I'd like to figure out how to add some css specifically to the newest images that were added, however I'm not really sure what the best way is to communicate that down to the view from the store without it getting really crufty...


Solution

  • You can just keep track of changes when the store sends an update message.

    store.addChangeEventListener((images) => {
      var last = this.state.newImageUrls || {};
      var now = {};
    
      images.forEach(function(img){
        if(!last[img.src]) now[img.src] = true;
      });
    
      this.setState({newImageUrls: now, images: images});
    });
    

    And in render you check if a given image src is new:

    var newImages = this.state.newImageUrls;
    ...
    images.map(function(x, i){
      return <img src={x.src} className={newImages[x.src] ? "new" : ""} />
    });